Whatever the nth capturing group matched
See also "Logical Operators" > "(X)".
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression(dog)
creates a single group containing the letters"d" "o"
and"g"
. The portion of the input string that matches the capturing group will be saved in memory for later recall via backreferences (as discussed below).Numbering
As described in http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html, capturing groups are numbered by counting their opening parentheses from left to right. In the expression((A)(B(C)))
, for example, there are four such groups:
((A)(B(C)))
(A)
(B(C))
(C)
Backreferences
The section of the input string matching the capturing group(s) is saved in memory for later recall via a backreference. A backreference is specified in the regular expression as a backslash (\
) followed by a digit indicating the number of the group to be recalled. For example, the expression(\d\d)
defines one capturing group matching two digits in a row, which can be recalled later in the expression via the backreference\1
.To match any 2 digits, followed by the exact same two digits, you would use
(\d\d)\1
as the regular expression:If you change the last two digits and the match will fail:Current REGEX is: (\d\d)\1 Current INPUT is: 1212 Finds the text "1212" starting at index 0 and ending at index 4.For nested capturing groups, backreferencing works in exactly the same way: Specify a backslash followed by the number of the group to be recalled.Current REGEX is: (\d\d)\1 Current INPUT is: 1234 No match found.