Probs
Probs

Reputation: 353

Regex match numbers with commas and points

I would like to match integers and floats using the re module. So if someone types one of the following input types, it should validate that it is a number:

- 1000
- 1.000
- 1,000
- ($1,000.98)
- -1.000
- 1.0
- $1,0000

Right now I am using the following:

"^[-+]?[0-9]+$"

Any help is appreciated

Upvotes: 0

Views: 2836

Answers (2)

anubhava
anubhava

Reputation: 785108

For the given input this regex should work:

^(?:[+-]|\()?\$?\d+(?:,\d+)*(?:\.\d+)?\)?$

RegEx Demo

Breakup:

  • ^ - Start
  • (?: - Start non-capturing group
    • [+-] - Match + or -
    • | - OR
    • \( - Match ( )? - End non-capturing group (optional)
  • \$? - Match $ (optional)
  • \d+ - Match 1 or more digits
  • (?: - Start non-capturing group
    • , - Match a comma
    • \d+ - Match 1 or more digits
  • )* - End non-capturing group (zero or more occurrence)
  • (?: - Start non-capturing group
    • \. - Match a DOT
    • \d+ - Match 1 or more digits
  • )? - End non-capturing group (optional)
  • \)? - Match a literal ) (optional) in the end
  • $ - End

Upvotes: 5

C.Molloy
C.Molloy

Reputation: 41

Hi I messed around on regexr.com and i got the following to match all 7 values

[0-9]?[-+.,]?[0-9]+[.]?[0-9]+

Hope this helps, and here is proof

Upvotes: 0

Related Questions