2008-12-22 74 views
24

如何使用正則表達式從字符串中提取double值。提取float/double值

import re 

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

你能否提供一些細節爲什麼你不能使用float(「4.5」)? – jfs 2008-12-22 04:41:00

回答

20

這裏是最簡單的方式。不要將正則表達式用於內置類型。

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

其實,這也是最安全的方式。考慮一些錯誤的輸入,比如`0..1`,`0.0.02`,正則表達式很難識別它。更糟糕的是,它會假裝它是正確的,併產生一些錯誤的答案。 – dspjm 2016-11-15 06:07:41

+0

技術上正確,但問題顯式指定了regexp。 – VillasV 2017-01-07 15:48:20

45

perldoc perlretut一個RegExp:

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

findall表達式是業務,謝謝 – reabow 2015-01-27 13:29:44

1

作爲蠻力的正則表達式的浮點數。還有的版本JF塞巴斯蒂安的差異較小:

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> 
+0

這不匹配沒有整數部分的浮點數,例如`.123`而不是`0.123`。 – 2013-05-02 11:57:22

9

對於解析int和float(點分離)值:

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

結果:

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