jazzabeanie
jazzabeanie

Reputation: 445

How to search and replace with a capture group in VBA

I want to use a regular expression in VBA to do a search, capture part of it, and then use that part in the replacement. For example, I want to run the search and replace on these lines:

(a4a)
(aHa)

And get a result of:

(b4b)
(bHb)

How do I capture the 2nd character and use it again in the replacement?

Upvotes: 1

Views: 1173

Answers (1)

jazzabeanie
jazzabeanie

Reputation: 445

In VBA, capture parts of the search with parenthesis () and use them in replacement with $ and the number of the capture occurrence. Note, normal parenthesis need to be escaped, which is the opposite of vim.

So in this case:

searchPattern = "\(a(.)a\)"
replacement = "(b$1b)"

Upvotes: 3

Related Questions