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

Mary-Kate Olsen
发布: 2024-10-21 13:00:30
原创
251 人浏览过

How to Extract Double Values from Strings Using Regular Expressions?

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

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

考虑以下代码片段:

<code class="python">import re

pattr = re.compile(???)    
x = pattr.match("4.5")</code>
登录后复制

解决方案:

使用正则从字符串中提取双精度值表达式,您可以使用以下正则表达式:

(?x)
   ^
      [+-]?\ *      # Optional sign and space
      (             # Integers or f.p. mantissas:
          \d+       # Integers of the form 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+)?  # Optionally match an exponent
   $
登录后复制

此正则表达式匹配以可选符号和空格开头,后跟整数或浮点尾数以及可选指数的字符串。

这是一个示例:

<code class="python">import re

re_float = re.compile("""(?x)
   ^
      [+-]?\ *      # Optional sign and space
      (             # Integers or f.p. mantissas:
          \d+       # Integers of the form 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+)?  # Optionally match an exponent
   $""")

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

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

如果您需要从较大的字符串中提取多个数字,您可以使用 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学习者快速成长!