- By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together.
- This allows you to apply a regex operator, e.g. a repetition operator, to the entire group.
- Note that only round brackets can be used for grouping. Square brackets define a character class, and curly braces are used by a special repetition operator.
- Besides grouping part of a regular expression together, round brackets also create a “backreference”.
- A backreference stores the part of the string matched by the part of the regular expression inside the parentheses.
- That is, unless you use non-capturing parentheses. Remembering part of the regex match in a backreference, slows down the regex engine because it has more work to do.
- If you do not use the backreference, you can speed things up by using non-capturing parentheses, at the expense of making your regular expression slightly harder to read.
- The regex «Set(Value)?» matches „Set” or „SetValue”. In the first case, the first backreference will be empty, because it did not match anything. In the second case, the first backreference will contain „Value”.
- If you do not use the backreference, you can optimize this regular expression into «Set(?:Value)?».
- The question mark and the colon after the opening round bracket are the special syntax that you can use to tell the regex engine that this pair of brackets should not create a backreference.
Use Back reference in regex
- To back reference is to use the search result of the previous group again in the same search.
- We define group by using round brackets
Example : (\d)(\w) where (\d) is the first group and (\w) is the second group - We can reference to these groups by using \1 and \2 where \1 is the digit and \2 is the word respectively.
- Let us see an example to clarify it more
Q & A
Find a digits in the search text that may have been repeated 4 or more than 4 times
Text :
123 13222234
3534534 214333332432
Search Result expected : 2222 and 33333
==================================================================
Regex : (\d)\1{3,}