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

DDD
Release: 2024-10-21 12:30:04
Original
251 people have browsed it

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

    This will output:

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

    This will return a list of extracted values, including:

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

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!

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
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!