0

Can you please explain these pattern for me? pattern = r"(.+) \1" and pattern = r"(.+) \2"

when i use the following script, there is no problem:

import re
pattern = r"(.+) \1"
match = re.match(pattern, "word word")
if match:
   print ("Match 1")

but when i change the pattern to r"(.+) \2" it rise an error. please explain exactly what is this pattern mean.

import re
pattern = r"(.+) \2"
match = re.match(pattern, "egg egg egg")
if match:
   print ("Match 1")
neilfws
  • 32,751
  • 5
  • 50
  • 63
  • `\1` is a back-reference; it'll match whatever group 1 matched. There is only **one group** in your pattern, so `\2` can't reference anything. – Martijn Pieters May 15 '17 at 11:07

1 Answers1

3

\1 is equivalent to re.search(...).group(1), the first parentheses-delimited expression inside of the regex. Since there is no 2nd group in your regex, that's why it is not working. If you add 2nd group, then it will work

import re
pattern = r"(.+)() \2"
match = re.match(pattern, "egg egg egg")
if match:
   print ("Match 1")
Match 1
akash karothiya
  • 5,736
  • 1
  • 19
  • 29