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

DDD
发布: 2024-10-21 12:30:04
原创
251 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!