Parts of a regular expression can be grouped so that they are treated as a single unit. Parts of a regular expression are grouped by enclosing them with parenthesis (). Grouping a subexpression has many uses such as for alternation on part of the whole regular expression, for repetitions, for text extraction and for backreferencing. (Extraction and backreferencing are discussed in later sections.)
Some grouping examples are displayed in the following table:
Regular Expression
‘/(straw|blue|rasp)berry/’
String that Matches: strawberry, blueberry, or raspberry
Regular Expression
‘/Blah( blah)*/’
String that Matches: Blah, Blah blah, Blah blah blah, Blah, blah, blah, blah,...
Regular Expression
‘/^(a|b)/’
String that Matches: Matches either a or b at the beginning of the line (note that ‘/^a|b/’ would match a at the beginning or any b anywhere).
Regular Expression
‘/y(es)?/i’
String that Matches: Y, y, or any case insensitive version of ‘yes’.