RexEx Search – Tip of Week #16

Regular expressions are an extremely versatile text-matching language that gives you incredible power when searching your documents and when used with replace operations, can greatly assist with repetitive changes to blocks of code.

regex

The basic regular expression search is easily done. You simply open the Find dialog through the Edit – Find and Replace – Find menu or with Ctrl-F (Edit.Find). Enable regular expression searching by ensuring the Use checkbox is selected and the drop-down list has Regular Expressions selected.

Enter your regular expression into the Find What text box and click on Find Next. The next match of your expression will be found in the document. As with normal matches, clicking Find Next again will find the next match. The next step is to learn the regular expression (also known as regex or regexp) syntax.

Regular expressions :

Regular expressions can be very complex, but basic expressions can be easy to master. Unlike normal searches, regular expressions designate a pattern of characters to match instead of a constant string. For example, square brackets in a regular expression define a set of characters (a character class). When you execute the search, it will match any one character out of the set of characters inside the brackets, so the expression [abcd] would match a, b, c, and d—but not z. You can also specify character ranges inside the brackets, so [a-d] is equivalent to the expression [abcd]. If you need to specify more than one range, simply add it to the first, so [a-z0-9] will match any letter or number. Regular expression characters in Visual Studio are not case sensitive unless you select the Match Case option in the Find dialog. This is a departure from most other regular expression syntax.

Normal alphabetic characters outside of special expressions match characters literally, similar to a normal Find, but can be combined with regular expressions to make them more flexible. This means that combining the set match with a literal match gives us a pattern such as var[12], which will match var1 and var2 but not var3.

If you want to match the string var[12], you’d need to escape the special characters, as in var\[12\].

More Regular Expressions.