提取float / double值

如何使用正则expression式从string中提取一个double值。

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

这是简单的方法。 不要使用正则expression式的内置types。

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

来自perldoc perlretutexpression式:

 import re re_float = re.compile("""(?x) ^ [+-]?\ * # first, match an optional sign *and space* ( # then match integers or fp mantissas: \d+ # start out with a ... ( \.\d* # mantissa of the form ab 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 

从较大的string中提取数字:

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

parsingint和float(点分隔符)值:

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

结果:

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

作为正式expression的powershell浮动。 JF Sebastian的版本有一些小的差异:

 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>