I need to find all matches in a string for a given regex. I\'ve been using findall()
to do that until I came across a case where it wasn\'t doing what I expecte
@aleph_null's answer correctly explains what's causing your problem, but I think I have a better solution. Use this regex:
regex = re.compile(r'\d+(?:,\d+)*')
Some reasons why it's better:
(?:...)
is a non-capturing group, so you only get the one result for each match.
\d+(?:,\d+)*
is a better regex, more efficient and less likely to return false positives.
You should always use Python's raw strings for regexes if possible; you're less likely to be surprised by regex escape sequences (like \b
for word boundary) being interpreted as string-literal escape sequences (like \b
for backspace).