Home >Backend Development >Python Tutorial >Why Does `re.findall()` Return Empty Results When Matching Floating-Point Numbers in Python?

Why Does `re.findall()` Return Empty Results When Matching Floating-Point Numbers in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 07:07:10794browse

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:

  • -? matches an optional minus sign.
  • d* matches optional digits.
  • .? matches an optional decimal separator.
  • d matches one or more digits.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn