re.search to get decimal number [closed]

I am trying to get a number from a text file. I need the full decimal number. The line looks like:

corner_lat: 49.0425000 decimal degrees

I'm trying this

 if "corner_lat" in line: nlines = re.search(r'(\d+)\D+', line).group(1) nlines = float(nlines) # type: print(nlines) 

But I get only one decimal (49.0). How should I change my re.search to get the full number?

1 Answer

Your pattern, (\d+) matches only digits and catches just the 49. In the next line you convert that 49 to a float resulting in 49.0.

Adjust the pattern to either match digits and dots or to match digits, one dot, followed by digits:

# match arbitrary number and order of digits and dots.
# Note that this also would match "49.123.4.5":
nlines = re.search(r'([\d.]+)\D+', line).group(1)
# or match N digits, ONE dot, N digits:
nlines = re.search(r'(\d+\.\d+)\D+', line).group(1)

You can also omit the \D part because regexes are by default greedy: they try to pick as many digits as possible while still fullfilling the overall pattern. In other words, it tries to find the longest possible sequence of digits, dot, digits and thus automatically stops at a non-digit (\D):

nlines = re.search(r'(\d+\.\d+)', line).group(1)

Note: We need to escape the dot \. when outside a character class because a dot matches any character. This is not needed when inside a character class, i.e. [.] doesn't match any character, but just a literal dot.

You Might Also Like