Home >Backend Development >Python Tutorial >Why Does `re.findall()` Return an Empty List When `re.search()` Finds a Match?
The re.findall() function can be confusing if it doesn't return the expected results when matching a string. Let's explore the reasons behind its behavior in a specific case.
Consider the following source string:
s = r'abc123d, hello 3.1415926, this is my book'
And the following pattern:
pattern = r'-?[0-9]+(\.[0-9]*)?|-?\.[0-9]+'
With re.search, we get the correct result:
m = re.search(pattern, s) print(m) # <_sre.SRE_Match object; span=(3, 6), match='123'>
However, re.findall returns an empty list:
L = re.findall(pattern, s) print(L) # []
There are two key aspects to consider:
To correctly match numeric values, use the following pattern instead:
pattern = r'-?\d*\.?\d+'
This pattern matches:
With this corrected pattern, re.findall will return the expected list:
['123', '3.1415926']
The above is the detailed content of Why Does `re.findall()` Return an Empty List When `re.search()` Finds a Match?. For more information, please follow other related articles on the PHP Chinese website!