Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract float/double value

Tags:

python

regex

How do I extract a double value from a string using regex.

import re  pattr = re.compile(???)     x = pattr.match("4.5")       
like image 617
Berlin Brown Avatar asked Dec 22 '08 04:12

Berlin Brown


People also ask

How do you extract a floating number from a string in Python?

To extract a floating number from a string with Python, we call the re. findall method. import re d = re. findall("\d+\.


2 Answers

A regexp from the 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 

To extract numbers from a bigger 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'] 
like image 161
jfs Avatar answered Sep 24 '22 06:09

jfs


Here's the easy way. Don't use regex's for built-in types.

try:     x = float( someString ) except ValueError, e:     # someString was NOT floating-point, what now? 
like image 20
S.Lott Avatar answered Sep 22 '22 06:09

S.Lott