Python matching a real/float number with regex

python, regex

Solution

[0-9]\.?[0-9]?

The first [0-9] will match once occurrence of a digit. The .? will match 0-1 periods [0-9]? will match 0-1 digits.

So, your regex will parse 1, 11, 1.1, but not 1.11 or 11.1

If you want to parse all of the above, I suggest the following.

([0-9]+(?:\.[0-9]+)?)(?:\s)

[0-9]+ - Match 1 or more digits \. - Match 1 period [0-9]*? - Match all remaining digits. ()? - Enter this regex 0 or 1 times.

Anything within parenthesis will be captured. If you see a regex enclosed in (?:...) it is a NON-capturing regex. BUT if that (?...) is enclosed in a (...), it will be captured by the (...) regex... it's kind of messy. But the above should work to capture only the number and not the space.

Problem

I'm not the best at re. Can anyone tell me if this pattern will work to return a single occurrence of a whole or decimal number before the occurrence of the literal,"each"? The number and the string each will be separated by a single space. ``` for each in parsed: if measure_string.find(each)>-1: r = re.compile("([0-9]\.?[0-9]?) "+each) b = re.match(r,measure_string) if b: return b, each ``` Thanks for taking a look.

Original source