简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM