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 expected. For example:
regex = re.compile('(\d+,?)+')
s = 'There are 9,000,000 bicycles in Beijing.'
print re.search(regex, s).group(0)
> 9,000,000
print re.findall(regex, s)
> ['000']
In this case search()
returns what I need (the longest match) but findall()
behaves differently, although the docs imply it should be the same:
findall()
matches all occurrences of a pattern, not just the first one assearch()
does.
Why is the behaviour different?
How can I achieve the result of
search()
withfindall()
(or something else)?