如何使用正则表达式从字符串中提取双精度值?

Mary-Kate Olsen
发布: 2024-10-21 12:42:31
原创
858 人浏览过

How to Extract Double Values from Strings Using Regex?

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

问题:如何使用正则表达式从字符串中分离双精度值?

解决方案:

要使用正则表达式从字符串中提取双精度值,可以使用复杂的正则表达式,例如:

<code class="python">import re
re_float = re.compile("""(?x)
   ^
      [+-]?\ *      # first, match an optional sign *and space*
      (             # then match integers or f.p. mantissas:
          \d+       # start out with a ...
          (
              \.\d* # mantissa of the form a.b or a.
          )?        # ? takes care of integers of the form a
         |\.\d+     # mantissa of the form .b
      )
      ([eE][+-]?\d+)?  # finally, optionally match an exponent
   $""")</code>
登录后复制

此模式匹配以十进制或科学记数法表示浮点数的字符串。要从字符串中提取数字,只需调用 re_float.match(string)。

例如:

<code class="python">m = re_float.match("4.5")
print(m.group(0))
# -> 4.5</code>
登录后复制

此代码将“4.5”打印到控制台。

从字符串中提取多个数字:

要从较大的字符串中提取多个数字,可以将 re.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))
# -> ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2',
#     '       1.01', '-.2', ' 123', ' .123']</code>
登录后复制

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

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