Home > Replace In Files > Understanding Regular Expressions

Understanding Regular Expressions

When the Regular expression checkbox is unchecked, Replace In Files will look for exact matches to the literal text you have entered into the Find field. That’s great if you want to find a simple string, such as ‘2010’. But what if you wanted to find a match ‘2008’, ‘2009’ and ‘2010’? You can construct searches like this using regular expressions.

Regular expressions enable you to search line-by-line for a pattern or template of characters, rather than simply find exact matches to the text you specify. Replace In Files uses the standard perl regex syntax to specify search patterns. This is the same syntax as that used by Araxis Merge and many other applications.

For a guide to regular expression syntax, please see Regular Expression Reference.

Example regular expressions for the ‘Find’ field

Show/hide this sectionSimple matches

Show/hide this sectionMatching whitespace

Show/hide this sectionMatching C++ comments

Show/hide this sectionCombining expressions

Referring back to the text matched by a regular expression when specifying replacement text

Let’s say you wish to update the copyright notices in a series of HTML files with a new finishing year. You might have notices such as:

<!-- Copyright 2008-2009 -->

and

<!-- Copyright 1993-2008 -->

You’d like these to become:

<!-- Copyright 2008-2010 -->

and

<!-- Copyright 1993-2010 -->

Now, you could run several different find and replace operations, one for each particular date range. Or you could match all copyright date-ranges with a regular expression such as:

^<!-- Copyright (\d\d\d\d)-\d\d\d\d -->$

The first four digits of the date range is placed into its own group by surrounding it with parentheses. In your replacement text, you can now refer back to this group by using a backslash and a group number, like this:

<!-- Copyright \1-2010 -->

The \1 in the replacement text is a back reference – it refers back to the first (\d\d\d\d) in the find regular expression. Using a back reference in this way, you can preserve the start date of the existing copyright date ranges, replacing only the end of the date range.

When searching using more complex expressions with several groups, \2 would refer to the second parenthetical grouping, \3 to the third, and so on.

Example regular expressions for the ‘Replace’ field

Below shows examples of using regular expressions to specify replacement text. For additional information see http://www.boost.org/doc/libs/1_39_0/libs/regex/doc/html/boost_regex/format/perl_format.html This link is to an external website.

Show/hide this sectionSwapping text

Show/hide this sectionPrepending text

Show/hide this sectionReplacing several alternatives with a single substitute