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"))
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"))
Shouldn't the
a*
match with thea
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.