Skip to content Skip to sidebar Skip to footer

Python Regex To Get Float Number From String

I am using regex to parse float number from the string. re.findall('[^a-zA-Z:][-+]?\d+[\.]?\d*', t) is the code that I used. There is a problem with this code. It is not parse th

Solution 1:

Use

re.findall(r"(?<![a-zA-Z:])[-+]?\d*\.?\d+", t)

See the regex demo

It will match integer and float numbers not preceded with letters or colon.

Details:

  • (?<![a-zA-Z:]) - a negative lookbehind that makes sure there is no ASCII letter or colon immediately before the current location
  • [-+]? - an optional + or -
  • \d* - zero or more digits
  • \.? - an optional dot
  • \d+ - 1+ digits

Solution 2:

The easiest thing you should be able to do here is just wrap the "number" part of your regular expression into a capture group, and then look at those capture groups.

re.findall("[^a-zA-Z:]([-+]?\d+[\.]?\d*)", t)

I just added parentheses around the "number" part of your search.


Post a Comment for "Python Regex To Get Float Number From String"