如何在Python中使用正则表达式提取浮点/双精度值?

Linda Hamilton
发布: 2024-10-21 12:05:02
原创
813 人浏览过

How to Use Regular Expressions to Extract Float/Double Values in Python?

使用正则表达式提取浮点/双精度值

在Python中,您可以利用正则表达式从字符串中提取浮点或双精度值。让我们探索 Perl 中强大的正则表达式:

(?x)
^
  [+-]?\ *      # Optional sign followed by optional whitespace
  (             # Match integers or floating-point mantissas
      \d+       # Whole numbers
      (
          \.\d* # Mantissa with decimal point (a.b or a.)
      )?        # Optional decimal point
     |\.\d+     # Mantissa without leading whole number (.b)
  )
  ([eE][+-]?\d+)?  # Optional exponent
$
登录后复制

例如,要从字符串中提取双精度值:

<code class="python">import re

# Create a regular expression pattern
re_float = re.compile(above_regexp)

# Match the pattern against a string
match = re_float.match("4.5")

# Extract the matched value
double_value = match.group(0)

print(double_value)  # Output: 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"""

numeric_values = re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s)

print(numeric_values)  # Output: ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2', '       1.01', '-.2', ' 123', ' .123']</code>
登录后复制

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

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