Grouping Similar Items in Parentheses

Use parentheses to enclose a group of related search elements. Parentheses limit scope on alternation and create substrings to enhance searches with metacharacters. For example, use parentheses to group the expression (abc), then apply the range quantifier {3} to find instances of the string "abcabcabc".

Using parentheses to group regular expressions.

Example 1: Use parentheses and a range quantifier to find instances of the string "abcabcabc".

  • Regex:
    (abc){3}
  • Matches:
    abcabcabc
    abcabcabcabc
    Note: In the second match, the match will actually be to the first nine characters only.
  • Doesn't Match:
    abc
    abcabc

Example 2: Use parentheses to limit the scope of alternative matches on the words gray and grey.

  • Regex:
    gr(a|e)y
  • Matches:
    gray
    grey
  • Doesn't Match:
    gry
    graey

Example 3: Use parentheses and "|" to locate past correspondence in a mail-filtering program. This regex finds a "To:" or a "From:" line followed by a space and then either the word "Smith" or the word "Chan".

  • Regex:
    (To:|From:)(Smith|Chan)
  • Matches:
    To:Smith
    To:Chan
    From:Smith
    To:Smith, Chan
    To:Smithe
    From:Channel4News
  • Doesn't Match:
    To:smith
    To:All
    To:Schmidt