【问题标题】:Extract float/double value提取浮点数/双精度值
【发布时间】:2022-11-19 22:21:19
【问题描述】:

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

import re

pattr = re.compile(???)    
x = pattr.match("4.5")      

【问题讨论】:

  • 您能否详细说明为什么不能使用 float("4.5")?

标签: python regex


【解决方案1】:

来自 perldoc perlretut 的正则表达式:

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
   $""")
m = re_float.match("4.5")
print m.group(0)
# -> 4.5

从更大的字符串中提取数字:

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

【讨论】:

  • 请注意,这也匹配整数(这是预期的,因为每个整数也是浮点数)
【解决方案2】:

这是简单的方法。不要将正则表达式用于内置类型。

try:
    x = float( someString )
except ValueError, e:
    # someString was NOT floating-point, what now?

【讨论】:

  • 其实,这也是最安全的方式。考虑一些错误的输入,比如0..1、0.0.02,正则表达式很难识别它。更糟糕的是,它会假装它是正确的并产生一些错误的答案。
  • 技术上正确,但问题明确指定了正则表达式。
【解决方案3】:

对于解析 int 和 float(点分隔符)值:

re.findall( r'd+.*d*', 'some 12 12.3 0 any text 0.8' )

结果:

['12', '12.3', '0', '0.8']

【讨论】:

  • 如果您可以提供一个程序来获取 int 或 float 但它不在字典或数组中,那么它会有所帮助。我有什么 str1 = "BIOS: version 2.0.0" 我想要什么 2.0.0 没有任何逗号或括号。
  • 您好,您可能会这样使用:re.findall( r'[d.]+', "BIOS: version 2.0.0" )
  • 更好:re.findall( r'[d.]{2,}|d+', "BIOS: version 2.0.0" )
  • 简单准确
【解决方案4】:

浮点数作为蛮力中的正则表达式。 J.F. 塞巴斯蒂安的版本有较小的差异:

import re
if __name__ == '__main__':
  x = str(1.000e-123)
  reFloat = r'(^[+-]?d+(?:.d+)?(?:[eE][+-]d+)?$)'
  print re.match(reFloat,x)

>>> <_sre.SRE_Match object at 0x0054D3E0>

【讨论】:

  • 这不匹配没有整数部分的浮点数,例如.123 而不是 0.123。
【解决方案5】:

请注意,这些答案均未涵盖有趣的边缘情况,例如“inf”、“NaN”、“-iNf”、“-NaN”、“1e-1_2_3_4_5_6”等。

(灵感来自埃里克在这里的回答Checking if a string can be converted to float in Python)

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 1970-01-01
    • 2018-02-23
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 2013-08-30
    • 1970-01-01
    相关资源
    最近更新 更多