We can use the contents of capturing groups
(...) not only in the result or in the replacement string, but also in the pattern itself.
Backreference by number: \N
A group can be referenced in the pattern using
N is the group number.
To make clear why that’s helpful, let’s consider a task.
We need to find quoted strings: either single-quoted
'...' or a double-quoted
"..." – both variants should match.
How to find them?
We can put both kinds of quotes in the square brackets:
['"](.*?)['"], but it would find strings with mixed quotes, like
'...". That would lead to incorrect matches when one quote appears inside other ones, like in the string
"She's the one!":
As we can see, the pattern found an opening quote
", then the text is consumed till the other quote
', that closes the match.
To make sure that the pattern looks for the closing quote exactly the same as the opening one, we can wrap it into a capturing group and backreference it:
Here’s the correct code:
Now it works! The regular expression engine finds the first quote
(['"]) and memorizes its content. That’s the first capturing group.
Further in the pattern
\1 means “find the same text as in the first group”, exactly the same quote in our case.
Similar to that,
\2 would mean the contents of the second group,
\3 – the 3rd group, and so on.
If we use
?: in the group, then we can’t reference it. Groups that are excluded from capturing
(?:...) are not memorized by the engine.
\1, in the replacement:
In the replacement string we use a dollar sign:
$1, while in the pattern – a backslash
Backreference by name:
If a regexp has many parentheses, it’s convenient to give them names.
To reference a named group we can use
In the example below the group with quotes is named
?<quote>, so the backreference is
<code>kullanınız, birkaç satır eklemek için ise
<pre>kullanın. Eğer 10 satırdan fazla kod ekleyecekseniz plnkr kullanabilirsiniz)