Reputation: 23
import re
if re.match(r'1{0}', 'foo').group() == '':
print(True)
Could someone explain why the condition is always satisfied?
The first character can be anything like:
1{0}
, 2{0}
, a{0}
etc
And why:
re.match(r'11{0}', 'foo').group()
# AttributeError: 'NoneType' object has no attribute 'group
Upvotes: 2
Views: 78
Reputation: 500713
From the documentation:
{m}
Specifies that exactly
m
copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example,a{6}
will match exactly six'a'
characters, but not five.
Therefore, 1{0}
would match exactly zero repetitions of the character 1
. This is the same as an empty regex, and would match anything.
Upvotes: 4
Reputation: 70715
Because {0}
tells it to match 0 repetitions of what it follows. 0 repetitions is an empty string. An empty string always matches.
Upvotes: 3