Home >Backend Development >Python Tutorial >Why Does `re.findall()` Return an Empty List When `re.search()` Finds a Match?

Why Does `re.findall()` Return an Empty List When `re.search()` Finds a Match?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 09:23:09113browse

Why Does `re.findall()` Return an Empty List When `re.search()` Finds a Match?

re.findall Behavior

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.

Problem Statement

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)  # []

Understanding the Issue

There are two key aspects to consider:

  1. Empty Match Capture Groups: re.findall returns captured texts from the match object, but in this pattern, there are no capturing groups. As a result, it returns empty strings.
  2. Character Escaping: The \. in the pattern matches two characters: and any character except newline. This is not intended for matching numeric values.

Solution

To correctly match numeric values, use the following pattern instead:

pattern = r'-?\d*\.?\d+'

This pattern matches:

  • -? - Optional minus sign
  • d* - Optional digits
  • .? - Optional decimal separator
  • d - One or more digits

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!

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