Home  >  Article  >  Backend Development  >  How to Use Regular Expressions to Extract Float/Double Values in Python?

How to Use Regular Expressions to Extract Float/Double Values in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-21 12:05:02815browse

How to Use Regular Expressions to Extract Float/Double Values in Python?

Extracting Float/Double Values with Regular Expressions

In Python, you can utilize regular expressions to extract floating-point or double values from strings. Let's explore a powerful regular expression from Perl:

(?x)
^
  [+-]?\ *      # Optional sign followed by optional whitespace
  (             # Match integers or floating-point mantissas
      \d+       # Whole numbers
      (
          \.\d* # Mantissa with decimal point (a.b or a.)
      )?        # Optional decimal point
     |\.\d+     # Mantissa without leading whole number (.b)
  )
  ([eE][+-]?\d+)?  # Optional exponent
$

For example, to extract a double value from a string:

<code class="python">import re

# Create a regular expression pattern
re_float = re.compile(above_regexp)

# Match the pattern against a string
match = re_float.match("4.5")

# Extract the matched value
double_value = match.group(0)

print(double_value)  # Output: 4.5</code>

To extract multiple numeric values from a larger string, you can use the findall() method:

<code class="python">s = """4.5 abc -4.5 abc - 4.5 abc + .1e10 abc . abc 1.01e-2 abc 
       1.01e-.2 abc 123 abc .123"""

numeric_values = re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s)

print(numeric_values)  # Output: ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2', '       1.01', '-.2', ' 123', ' .123']</code>

The above is the detailed content of How to Use Regular Expressions to Extract Float/Double Values 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