4

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?

8

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).

  • Submitted an edit request, but I believe the search string should be '(Dim.*?)(As)'. Adding the ? causes the search to take as little as possible, rather than matching the first Dim with the last As -- actually, this is only an issue in singleline searches, my bad – Caraxian Oct 1 '14 at 21:32
1

This can be done with a lookbehind and lookahead. For example: Find:

(?<=Dim)(.*?)(?=As)

Replace With:

\1'

This should do what you are attempting to do. The '\1' in the replace matches the text between 'Dim' and 'As', allowing you to add a comment.

Edit

As a side note after I tested, this only works with Replace All

  • Strange, I wonder why it only works with Replace All. Anyone know? – DACrosby Oct 1 '14 at 21:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.