tags:

views:

2715

answers:

3

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

import re

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

A: 

I'm assuming your string contains text apart from just a floating point value. If the whole string is just a number, you can just use:

 float(string)

You can use something like this to find all the floats in the string:

 regex = "\d+\.\d+"
 match = re.findall(regex, mystring)
 x = float(match.group(1))
Kamil Kisiel
Your regex will only match one digit either side of the decimal. The .* probably isn't necessary either.
too much php
You fixed the problems Peter pointed out, but now your syntax is all wrong. findall() returns a list of strings, not a MatchObject, so you can't call group(1) on it; did you mean search() instead of findall()? But change it to "group()", because there's no group #1 in your regex now.
Alan Moore
+1  A: 

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']
J.F. Sebastian
+6  A: 

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?
S.Lott