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
Release: 2024-12-19 09:23:09
Original
149 people have browsed it

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'
Copy after login

And the following pattern:

pattern = r'-?[0-9]+(\.[0-9]*)?|-?\.[0-9]+'
Copy after login

With re.search, we get the correct result:

m = re.search(pattern, s)
print(m)  # <_sre.SRE_Match object; span=(3, 6), match='123'>
Copy after login

However, re.findall returns an empty list:

L = re.findall(pattern, s)
print(L)  # []
Copy after login

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+'
Copy after login

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']
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template