How to Extract Double Values from Strings Using Regex?

Mary-Kate Olsen
Release: 2024-10-21 12:42:31
Original
856 people have browsed it

How to Extract Double Values from Strings Using Regex?

Extraction of Floating-Point Values from Strings Using Regex

Question: How can a regex be used to isolate a double value from a string?

Solution:

To extract a double value from a string using regex, a sophisticated regexp can be used, such as:

<code class="python">import re
re_float = re.compile("""(?x)
   ^
      [+-]?\ *      # first, match an optional sign *and space*
      (             # then match integers or f.p. mantissas:
          \d+       # start out with 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+)?  # finally, optionally match an exponent
   $""")</code>
Copy after login

This pattern matches strings that represent floating-point numbers in either decimal or scientific notation. To extract the number from a string, simply call re_float.match(string).

For example:

<code class="python">m = re_float.match("4.5")
print(m.group(0))
# -> 4.5</code>
Copy after login

This code prints "4.5" to the console.

Extraction of Multiple Numbers from a String:

To extract multiple numbers from a larger string, the re.findall() function can be used with the same regex pattern:

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

The above is the detailed content of How to Extract Double Values from Strings Using Regex?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!