Home  >  Article  >  Backend Development  >  How to Extract Double Precision Floating-Point Values from Strings with Regex?

How to Extract Double Precision Floating-Point Values from Strings with Regex?

DDD
DDDOriginal
2024-10-21 12:13:33891browse

How to Extract Double Precision Floating-Point Values from Strings with Regex?

Extracting Double Precision Floating-Point Values from Strings with Regular Expressions

In this article, we will explore a question often encountered in programming: how to extract double precision floating-point numbers from a text string using the Python re module for regular expressions.

Regex Pattern for Double Precision

To match double precision floating-point values, we can use a regular expression that captures optional signs, integral or fractional parts, and an optional exponent. The following pattern is an example from the Perl documentation:

<code class="python">re_float = re.compile("""(?x)
   ^
      [+-]?\ *      # optional sign and space
      (             # integer or fractional mantissa:
          \d+       # start out with digits...
          (
              \.\d* # mantissa of the form a.b or a.
          )?        # ? for integers of the form a
         |\.\d+     # mantissa of the form .b
      )
      ([eE][+-]?\d+)?  # optional exponent
   $""")</code>

Matching and Extracting

To match a double precision value with this pattern, we can use the match method on a compiled regular expression object:

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

This extracts the portion of the string that matches the pattern, in this case, the entire string.

Extracting Multiple Values

If we have a larger string containing multiple double precision values, we can use the findall method to extract all matching values:

<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))
# prints ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2',
#     '       1.01', '-.2', ' 123', ' .123']</code>

This pattern matches any double precision floating-point value, regardless of spaces or surrounding text, and extracts it as a list of strings.

The above is the detailed content of How to Extract Double Precision Floating-Point Values from Strings with Regex?. 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