-7

Shouldn't the a* of the following regex match with the a in the string, which only leaves d so the ad$ shouldn't match, right? Why is this true?

pattern = r"a*ad$"

print(re.search(pattern, "ad"))
bobble bubble
  • 11,968
  • 2
  • 22
  • 34
Dima
  • 145
  • 7

1 Answers1

0

Shouldn't the a* match with the a in the string?

No, because * means a can match zero or more times, so the '' empty string also matches that expression. That leaves 'ad' after the initial empty string to match for the remainder of the expression.

A regex will consider both options here (both '', the empty string, and 'a' satisfy the a* pattern).

Use a+ if you wanted the pattern to match at least once.

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
  • Oh ok, I didn't know it checks all options. – Dima Apr 29 '17 at 17:46
  • This is why there is such a thing as [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html), where you can make a regex engine try out an exponential number of options. – Martijn Pieters Apr 29 '17 at 17:47