Home  >  Article  >  Backend Development  >  How to Extract Double Values from Strings Using Regular Expressions?

How to Extract Double Values from Strings Using Regular Expressions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-21 13:00:30251browse

How to Extract Double Values from Strings Using Regular Expressions?

Extracting Double Values from Strings Using Regex

Problem: How can you isolate a double value from a string using a regular expression?

Consider the following code snippet:

<code class="python">import re

pattr = re.compile(???)    
x = pattr.match("4.5")</code>

Solution:

To extract a double value from a string using a regular expression, you can use the following regular expression:

(?x)
   ^
      [+-]?\ *      # Optional sign and space
      (             # Integers or f.p. mantissas:
          \d+       # Integers of the form a...
          (
              \.\d* # Mantissa of the form a.b or a.
          )?        # ? takes care of integers of the form a
         |\.\d+     # Mantissa of the form .b
      )
      ([eE][+-]?\d+)?  # Optionally match an exponent
   $

This regular expression matches strings that start with an optional sign and space, followed by an integer or floating-point mantissa, and an optional exponent.

Here's an example:

<code class="python">import re

re_float = re.compile("""(?x)
   ^
      [+-]?\ *      # Optional sign and space
      (             # Integers or f.p. mantissas:
          \d+       # Integers of the form a...
          (
              \.\d* # Mantissa of the form a.b or a.
          )?        # ? takes care of integers of the form a
         |\.\d+     # Mantissa of the form .b
      )
      ([eE][+-]?\d+)?  # Optionally match an exponent
   $""")

m = re_float.match("4.5")
print(m.group(0))
# -> 4.5</code>

Extracting Multiple Numbers from a String:

If you need to extract multiple numbers from a larger string, you can use the findall() function:

<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"""
print(re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s))
# -> ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2',
#     '       1.01', '-.2', ' 123', ' .123']</code>

This regular expression will match any number that consists of an optional sign, space, a combination of integer and optional fractional part, and an optional exponent notation.

The above is the detailed content of How to Extract Double Values from Strings Using Regular Expressions?. 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