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.