Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of results of re.findall guaranteed?

Will the list of matches returned by re.findall always be in the same order as they are in the source text?

like image 301
Old Geezer Avatar asked Feb 01 '16 14:02

Old Geezer


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 does Findall work Python?

How Does the findall() Method Work in Python? The re. findall(pattern, string) method scans string from left to right, searching for all non-overlapping matches of the pattern . It returns a list of strings in the matching order when scanning the string from left to right.

What is the difference between Finditer and Findall?

But finditer and findall are finding different things. Findall indeed finds all the matches in the given string. But finditer only finds the first one, returning an iterator with only one element.

What is difference between Search () and Findall () methods in Python?

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

Yes, as stated in the re module docs:

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.

like image 156
Rob Murray Avatar answered Sep 17 '22 16:09

Rob Murray


Quoting the documentation:

The string is scanned left-to-right, and matches are returned in the order found.

So, yes - the list of matches returned by re.findall will always be in the same order as in the source text.

like image 21
gtlambert Avatar answered Sep 18 '22 16:09

gtlambert