首页  >  文章  >  后端开发  >  如何使用正则表达式从字符串中提取浮点值?

如何使用正则表达式从字符串中提取浮点值?

DDD
DDD原创
2024-10-21 12:30:04252浏览

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

使用正则表达式从字符串中提取浮点值

考虑从字符串中提取双精度值的任务。要使用正则表达式实现此目的,涉及以下步骤:

  1. 构造正则表达式:

    <code class="python">import re
    
    pattr = re.compile(???)
    x = pattr.match("4.5")</code>
  2. 使用 Perl 兼容的正则表达式:
    Perl 文档中用于提取浮点值的合适正则表达式是:

    <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. 查找并检索匹配项:
    要提取双精度值,请将已编译的正则表达式应用于所需的字符串:

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

    这将输出:

    4.5
  4. 从字符串中提取多个值:
    要从较大的字符串中提取多个浮点值,请使用 findall() 方法:

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

    这将返回提取值的列表,包括:

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

以上是如何使用正则表达式从字符串中提取浮点值?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn