The special symbols “{” and “}” group regular expressions for reference purposes. They permit the text matched by the expression within “{ }” to be referenced again in the search string or to be included as part of the replacement text.

An expression may contain up to 9 groups which are referenced by number, “\1” through “\9”. The groups are numbered in the order of their opening “{”.Groups may also be nested. Groups may be referenced in either a latter part of the regular expression or in the replacement string. This allows portions of the matched text to be used as parts of the replacement text.

The character “&” has a special meaning only in a replacement string and references the entire text matched by the search.

Consider the expression “the {man}|the {woman}”. If the matched text is “the man”, “\1” is “man” and “\2” is empty (null). Now consider the expression “{the {[a-z]+}} has”. If the matched text is “the woman has”, “\1” is “thewoman” and “\2” is “woman”.

{[a-z][a-z][a-z]}\1
Matches two contiguous occurrences of the same three letters. Will match “nownow”, “powpow”, etc.
{.*}\1
Matches any repeating text. Will match “nn”, “nownow”, “12341234”, etc.
^{.*}\1$
Matches a line consisting of two repeated occurrences of the same text (identical right and left halves).
^{.*}\N\1$
Matches two identical lines which occur together. (Can be used to find duplicate lines after sorting.)

Precedence

The order of precedence of the regular expressions operators is:

Highest > (to) Lowest

\\ > [ ] > * +  ? > { } > Concatenations > |

Groups and Replacement Examples

These examples show search and replacement strings using regular expressions. They illustrate how groups of matched text can be used as part of the replacement string. Be sure that the option ( ) Reg-Exp is selected in the Search/Replace dialog box.

Search: [A-Z][a-z]*
Search for the next capitalized word. Note that it will also match the single letter word “A”
Search: 0x[0-9a-fA-F]+
Search for the next hexadecimal number in a “C” program. It searches for “0x”, followed by one or more hexadecimal digits.
Search: ^{.+}$\N\1$
Search for a line that is duplicated on the next line.
Search: .*,
Replace:
Delete all text up to a comma on the next line which contains a comma. (Remember that the entire matching text must occur on one line.)
Search: {[Hh]}ello
Replace: \1i
Searches for “Hello” or “hello”, and replaces it with “Hi” or “hi” respectively.
Search: [Hh]ello
Replace: &~world
Searches for “Hello” or “hello”, and replaces it with “Hello~world” or “hello~world” respectively. The “&” references the entire text matched by the search. Note that the grouping characters “{ }” are NOT needed in order to use “&”.

Related Resources