+ 1
What actually '\1' special character matches in any re.
Can anyone explain in detail how this 'r"(.+) \1"' pattern actually matches. I know it match string having 2 space separated words which are same. But I want to know how this is actually been done, i.e what actually does this '\1' denotes. (.+) is a group which matches any any set of one or more characters, except space, but I'm not able to understand this '\1' thing.
1 Respuesta
+ 4
This is a so-called backreference - a capturing group is referred back to with using its number. So whenever your regex finds a match for the first capturing group (a single one in your case), \1 tells it to look for that exact match again (another occurence of the same expression).
If you have several capturing groups in your expression, you can refer back to any of them.
Check out how it can be utilized to find prime numbers:
https://code.sololearn.com/cgEoWC8lFuCk/?ref=app