regular expression for numbers without their end character that connect to them

Viewed 66

I need regular expression for numbers that can be negative, with commas or decimal.

For examples: 12 +12 -12.0 -12,345.5466 +12,345,678,678 0.154

But not pass: "500." or "500,". I want that 500 will return as a number without the point or the comma that connect to the number.

The regular expression that I wrote is:

[-+]?((0|([1-9](\d*|\d{0,2}(,\d{3})*)))(\.\d*[0-9])?)(?!\S)

It is work at the correct numbers (like the examples), but It don't work for the '500,' or '500.'

1 Answers

Assuming you want to match 500 in 500. and 500,, you should bear in mind that (?!\S) requires a whitespace or end of string immediately to the right.

You may fix the problem with

[-+]?(?:0|[1-9](?:\d{0,2}(?:,\d{3})*|\d*))(?:\.\d+)?(?!\d)

See this regex demo, and note that this can be further enhanced depending on what contexts you need to exclude.

I replaced (?!\S) with (?!\d) at the end to fail the match if there is a digit, not any non-whitespace char, immediately on the right.

Note also that I removed unnecessary groups and converted all capturing groups to non-capturing.

Also, pay attention to the (?:,\d{3})*|\d*) group, where I swapped the alternatives since the first one is more specific and should go first.

Details

  • [-+]? - an optional - or +
  • (?:0|[1-9](?:\d{0,2}(?:,\d{3})*|\d*)) - 0 or
    • [1-9] - a non-zero digit
    • (?:\d{0,2}(?:,\d{3})*|\d*) - either
      • \d{0,2}(?:,\d{3})* - zero, one or two digits, and then zero or more occurrences of a comma and three digits
      • | - or
      • \d* - zero or more digits
  • (?:\.\d+)? - an optional sequence of . and one or more digits
  • (?!\d) - a negative lookahead that fails the match if there is a digit immediately to the right of the current location.
Related