Home > Backend Development > Python Tutorial > Why Does `re.findall` Fail to Find Numbers in a String When `re.search` Succeeds?

Why Does `re.findall` Fail to Find Numbers in a String When `re.search` Succeeds?

Mary-Kate Olsen
Release: 2024-12-29 13:21:11
Original
833 people have browsed it

Why Does `re.findall` Fail to Find Numbers in a String When `re.search` Succeeds?

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

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:

  1. Capturing Groups: re.findall extracts and returns only captured text when the regex pattern contains capturing groups.
  2. Literal Backslash Matching: The \ within the pattern attempts to match a literal , rather than the intended . character.

Regex Modification

To address this, we can modify the pattern to remove redundant capturing groups and match numbers correctly:

pattern = r'-?\d*\.?\d+'
Copy after login

This pattern will match:

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

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

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!

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