Python-提取浮点/双精度值

发布于 2021-02-02 23:10:45

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

import re

pattr = re.compile(???)    
x = pattr.match("4.5")  
关注者
0
被浏览
63
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    是简单的方法。请勿将regex用于内置类型。

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


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    来自的正则表达式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']
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看