We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The backreference placeholder \1 is substituted with the substring that matches the group 1 pattern (\2 is for group 2, etc).
Their use is maybe a little more obvious when used with replace/sub, where you not only want to find a pattern but also add to it or alter it; for example find all 'b' or 'f' and put arrows around them:
Group 1 contains (\w), which matches 'a', so \1 now becomes 'a' and the regex will only be true if the next char is also 'a'.
The next char is 'b' so regex gives up on 'a' and looks for something else that matches \w,
This time (\w) matches 'b', and \1 becomes a 'b'; since the next character in the string is also a 'b' the regex is satisfied, it stops searching, and returns 'bb'.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Super Reduced String
You are viewing a single comment's thread. Return to all comments →
\1
is a regex backreference.The backreference placeholder
\1
is substituted with the substring that matches the group 1 pattern (\2
is for group 2, etc).Their use is maybe a little more obvious when used with
replace/sub
, where you not only want to find a pattern but also add to it or alter it; for example find all'b'
or'f'
and put arrows around them:So, given string
'abbc'
and patternr'(\w)(\1)'
:(\w)
, which matches'a'
, so\1
now becomes'a'
and the regex will only be true if the next char is also'a'
.'b'
so regex gives up on'a'
and looks for something else that matches\w
,(\w)
matches'b'
, and\1
becomes a'b'
; since the next character in the string is also a'b'
the regex is satisfied, it stops searching, and returns'bb'
.