-1

why the second print result is None:

import re
pattern=r"(.+) \1" #notice that there is whitespace here before the backslash
match=re.match(pattern,"abc abc")
if match:
    print(1)   #1 was printed
match=re.match(pattern,"abc abd")
print(match)   # None

Additionally,please give me another example for the usage of '\2'. Thx a lot.

Eric Ben
  • 21
  • 5

1 Answers1

1

Because in second example you have different values, abc and abd.

According to py mans, \number

Matches the contents of the group of the same number

https://docs.python.org/3.7/library/re.html

This means, it matches the contents of the group, not group's regular expression, so the second part is expected to be the same. This is the way to find other occurrences of the match.

Example for \2 is below:

(.+) (.+) \1 \2

will match

hello kitty hello kitty

3limin4t0r
  • 13,832
  • 1
  • 17
  • 33
grapes
  • 6,688
  • 1
  • 13
  • 29