Reputation: 207
regex with quantifier and grouping in python
p = re.compile('[29]{1}')
p.match('29')
why does 29 match p? i thought i explicitly said it's [29] (2 or 9) with {1} quantifier. Shouldn't it be JUST 2 OR 9? Or does it match the first group and not care about the rest thanks!
Upvotes: 0
Views: 48
Reputation: 5647
It is matching because it matches the sub-string '2'. The way regex works is that it returns true is there exists any substring inside the string that matches. The regex you are using would match '46657467562374746', because it contains a '2'. If you need the whole thing to match from beginning to end, you need to use anchors:
p = re.compile('^[29]{1}$')
p.match('29')
The hat (^) represents the beginning of the string and the dollar ($) represents the end of the string. So now this will only match if the whole sting is a single 2 or a single 9, instead of just containing a 2 or 9.
Upvotes: 2