Grouping and Captured Groups
Grouping alternatives
A better syntax for \bJane\b|\bJanet\b is \b(Jane|Janet)\b using () for grouping alternatives. However this also creates a captured group, if you don't need any captured group to reuse, see Noncapturing
Noncapturing groups
\b(?:Jane|Janet)\b disables group capturing using (?:), it won't capture the group when matching, benefit to better performance.
Group with mode modifier
Use any of (?i:<regex>) or (?s:<regex>) or (?m:<regex>) to annotate grouped alternatives
\b(?i:Jane|Janet)\b
To combine different modes:
(?ism:<regex>)enablescase-insensitive,singlelineandmultiline(?-ism:<regex>)disablescase-insensitive,singlelineandmultiline(?i-sm:<regex>)enablescase-sensitiveand disablessinglelineandmultiline
Backreference
Reference the first nine capturing groups with a backslash followed by a single digit one through nine(\1 to \9). For groups 10 through 99, use \10 to \99 The following regex matches date like 2008-08-08 and 2007-07-07.
\b\d\d(\d\d)-\1-\1\bIf backreferences are before any capturing groups, they fails to match anything.
Named group and named backrefernces
Assign a descriptive name for groups instead of numbers.
The previous example can be written as following:
\b\d\d(?<tailing>\d\d)-\k<tailing>-\1\bNamed group flavors:
| flavor | syntax |
|---|---|
| .NET, Java 7, PCRE 7, Perl 5.10, Ruby 1.9 | (?<name>regex) |
| .NET, PCRE 7, Perl 5.10, Ruby 1.9 | (?'name'regex) |
| Python, PCRE 4, Perl 5.10, RUby 1.9 | (?P<name>regex) |
Backreference flavours:
| flavor | syntax |
|---|---|
| .NET, Java 7, PCRE 7, Perl 5.10, Ruby 1.9 | \k<name> |
| .NET, PCRE 7, Perl 5.10, Ruby 1.9 | \k'name' |
| Python, PCRE 4, Perl 5.10, Ruby 1.9 | (?P=name) |
INFO
<> are not placeholder in tables above.