re.findall Behaves Unpredictably
With the original string and pattern as defined below:
s = r'abc123d, hello 3.1415926, this is my book' pattern = r'-?[0-9]+(\.[0-9]*)?|-?\.[0-9]+'
re.search accurately finds a match, while re.findall yields an empty list. This behavior, which contradicts the expected output of ['123', '3.1415926'], raises the question of why re.findall does not produce this result.
Understanding the Issue
Two key considerations are at play here:
Regex Modification
To address this, we can modify the pattern to remove redundant capturing groups and match numbers correctly:
pattern = r'-?\d*\.?\d+'
This pattern will match:
Results
Using this modified pattern, re.findall will produce the expected output:
import re L = re.findall(pattern, s) print(L) # Output: ['123', '3.1415926']
The above is the detailed content of Why Does `re.findall` Fail to Find Numbers in a String When `re.search` Succeeds?. For more information, please follow other related articles on the PHP Chinese website!