Bryan K.
Bryan K.

Reputation: 165

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 the number if there is no space between number and any character. For Example, the expect output from "0|1|2|3|4|5|6|7|8|9" is [0,1,2,3,4,5,6,7,8,9], but it returns "[|1,|2,|3,...].

Is there any way to solve this kind of problem?

Upvotes: 3

Views: 7689

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

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

Upvotes: 4

Shawn Tabrizi
Shawn Tabrizi

Reputation: 12434

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.

Upvotes: 1

Related Questions