0

In the following code, I expect the program to print "Match", because "\D+\d" matches the "x4" part of the string. But it does not print anything. What is the problem?

import re
pattern = r"\D+\d"
if re.match(pattern, "1x4"):
    print("Match");

Thanks

styvane
  • 59,869
  • 19
  • 150
  • 156

1 Answers1

2

Your assumption that re.match can match anywhere inside a string is wrong.

https://docs.python.org/2/library/re.html#re.RegexObject.match

If zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Use re.search() instead.

recursive
  • 83,943
  • 34
  • 151
  • 241