How to replace around a wildcard in a regex search

find and replacenotepadregex

I'm trying to comment out all of the variable type declarations in a script I have, but I've run into this problem a few other times. I'd like to match a string, followed by a variable name, followed by a string and replace the exact text but with a single quote in front of the second string.

For example:

Dim variableName As Boolean
Dim variableName2 As String

should become:

Dim variableName 'As Boolean
Dim variableName2 'As String

Now, a problem is the I also have "As" strings elsewhere in the code that shouldn't be replaced, so a simple find/replace wont work.

I'm using NotePad++ and have the following regex that matches my declarations correctly:

Dim.*As

But I can't figure out what to put in place of the .* in the replace field. Dim.*'As obviously replaces the wildcard string with a literal .*, which is no good.

Any ideas?

Best Answer

You can use RegEx "capture groups" to specify sections you want to capture and keep, and replace the rest.

In Notepad++ capture groups are represented by brackets (( and )), and you can put their content into the "Replace" by using notation such as \1, \2, etc. for each capture group you added (in order of appearance).

So, change your search RegEx to (Dim.*)(As), which will find things as it did for you originally, but makes two capture groups. One before where you want to insert the ', and one after.

To this will find Dim variableName As Boolean as before, and the two capture groups would contain Dim variableName and As Boolean.

For the Replace field in Notepad++, use \1'\2; this will replace the matched text with the first capture group, then the ', followed by the second capture group.

Perform your replace, and Dim variableName As Boolean becomes Dim variableName 'As Boolean (etc).

Related Question