Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python re.findall print all patterns

>>> match = re.findall('a.*?a', 'a 1 a 2 a 3 a 4 a')
>>> match
['a 1 a', 'a 3 a']

How do I get it to print

['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a']

Thank you!

like image 674
Hee Avatar asked Jul 04 '13 10:07

Hee


People also ask

Does re Findall return a list?

findall() is probably the single most powerful function in the re module. Above we used re.search() to find the first match for a pattern. findall() finds *all* the matches and returns them as a list of strings, with each string representing one match.

How can I find all matches to a regular expression in Python?

findall(pattern, string) returns a list of matching strings. re. finditer(pattern, string) returns an iterator over MatchObject objects.

How do I search for multiple patterns in Python?

Search multiple words using regex Use | (pipe) operator to specify multiple patterns.

What does the search () and Findall () method return?

findall() module is used to search for “all” occurrences that match a given pattern. In contrast, search() module will only return the first occurrence that matches the specified pattern. findall() will iterate over all the lines of the file and will return all non-overlapping matches of pattern in a single step.


2 Answers

I think using a positive lookahead assertion should do the trick:

>>> re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')
['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a']

re.findall returns all the groups in the regex - including those in look-aheads. This works because the look-ahead assertion doesn't consume any of the string.

like image 83
Volatility Avatar answered Oct 02 '22 11:10

Volatility


You may use alternative regex module which allows overlapping matches:

>>> regex.findall('a.*?a', 'a 1 a 2 a 3 a 4 a', overlapped = True)
['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a']
like image 28
ovgolovin Avatar answered Oct 02 '22 11:10

ovgolovin