What does it mean to have a \number
in a regex in java.
Let's say I have something like \1
or \2
. What does this mean and how is it used?
An example would be really helpful.
Thanks
What does it mean to have a \number
in a regex in java.
Let's say I have something like \1
or \2
. What does this mean and how is it used?
An example would be really helpful.
Thanks
Backreferences match the same text as previously matched by a capturing group. Suppose you want to match a pair of opening and closing HTML tags, and the text in between. By putting the opening tag into a backreference, we can reuse the name of the tag for the closing tag. Here's how:
<([A-Z][A-Z0-9]*)\b[^>]*>.*?</\1>
This regex contains only one pair of parentheses, which capture the string matched by
[A-Z][A-Z0-9]*
The backreference
\1
(backslash one) references the first capturing group.\1
matches the exact same text that was matched by the first capturing group. The/
before it is a literal character. It is simply the forward slash in the closing HTML tag that we are trying to match.
For more details and examples check: http://www.regular-expressions.info/backref.html
\
usually is used at the start of the construction of a match.
It also represents an escape character.