Home >Backend Development >Python Tutorial >Why Does `re.findall()` Return Empty Results When Matching Floating-Point Numbers in Python?
re.findall Misbehavior: Unwanted Empty Results
In the given scenario, while re.search() successfully extracted the intended numerical value "123" from the source string, re.findall() unexpectedly produced an empty result.
Upon investigation, the culprit was identified as the r'\.' portion of the regex pattern. Within raw strings (prefixed with r), \ is treated literally, matching a backslash character followed by any character except a newline. However, this is not the intended behavior for capturing floating-point numbers.
To rectify the issue, the corrected pattern, -?d*.?d , follows these principles:
Using this revised pattern, re.findall() now correctly identifies the numerical values in the source string:
import re s = r'abc123d, hello 3.1415926, this is my book' pattern = r'-?\d*\.?\d+' L = re.findall(pattern, s) print(L) # Output: ['123', '3.1415926']
Remember, for re.findall() to return match values without capturing groups, the pattern must be free of any capturing groups or non-capturing groups (e.g., (?:)), unless there are backreferences within the pattern.
The above is the detailed content of Why Does `re.findall()` Return Empty Results When Matching Floating-Point Numbers in Python?. For more information, please follow other related articles on the PHP Chinese website!