-2

I want to extract a float number from the string:

"{start Time : 123.24,"

I tried using re.findall like this:

number = re.findall("\d.\d", lines[i]) 

Where lines[i] is above string.

Which only returns only 3.2 (first decimal place).

How can I extract float number regardless its number of decimal places?

mkrieger1
  • 14,486
  • 4
  • 43
  • 54

3 Answers3

5

As noted by Tim, if your input is JSON, parse it as JSON; don’t faff around with regex.

But a simple fix to your regex is the use of quantifiers (and use raw string literals, and escape the dot):

number = re.findall(r"\d+\.\d+", lines[i]) 
Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
0

My solution with regex. But it would only exstract one float number from the string.

import re
str_in = "{start Time : 123.24,"

regex = re.compile(r"[0-9]+.[0-9]*")

elem = (re.search(regex, str_in))

result = float(elem.group())
Fabián Montero
  • 1,440
  • 11
  • 31
Marcin
  • 129
  • 10
0

If you don't want to use JSON, try the following regex:

\d+\.\d+

The + means 1 or more. Which will capture all the numbers.

So your code would look like this:

number = re.findall("\d+\.\d+", lines[i]) 

A good place to learn/test regexes is this website: https://pythex.org/

Fabián Montero
  • 1,440
  • 11
  • 31