Home  >  Article  >  Backend Development  >  How Can Regular Expressions Be Used to Extract Floating-Point Values from Strings?

How Can Regular Expressions Be Used to Extract Floating-Point Values from Strings?

DDD
DDDOriginal
2024-10-21 12:30:04252browse

How Can Regular Expressions Be Used to Extract Floating-Point Values from Strings?

Extracting Floating-Point Values from Strings with Regular Expressions

Consider the task of extracting a double value from a string. To achieve this using a regular expression, the following steps are involved:

  1. Construct the Regexp:

    <code class="python">import re
    
    pattr = re.compile(???)
    x = pattr.match("4.5")</code>
  2. Use Perl-Compatible Regular Expressions:
    A suitable regexp from the Perl documentation for extracting floating-point values is:

    <code class="python">re_float = re.compile("""(?x)
    ^
       [+-]?\ *      # an optional sign and space
       (             # integers or f.p. mantissas
           \d+       # start with a ...
           (           # ? takes care of integers
               \.\d* # mantissa a.b or a.
           )?
          |\.\d+     # mantissa .b
       )
       ([eE][+-]?\d+)?  # optionally match an exponent
    $""")</code>
  3. Find and Retrieve Matches:
    To extract the double value, apply the compiled regexp to the desired string:

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

    This will output:

    4.5
  4. Extract Multiple Values from a String:
    To extract multiple floating-point values from a larger string, 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"""
    print(re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s))</code>

    This will return a list of extracted values, including:

    ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2', '       1.01', '-.2', ' 123', ' .123']

The above is the detailed content of How Can Regular Expressions Be Used to Extract Floating-Point Values from Strings?. 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