Reputation: 147
I am using regex method to check that string contains only numbers and just one comma and accept (not prefix or postfix)
EX-> 123,456 Accepted
EX-> ,123456 NOT accepted
EX-> 123456, NOT accepted
I am using below regex but it does not work, it allows to repeat commas and only works for prefix commas
[0-9]+(,[0-9]+)*
Can anyone help me?
Upvotes: 1
Views: 2297
Reputation: 163642
To allow a single comma and not match when surrounded a comma, you could make use of a word boundary and lookarounds (if supported) to assert not a comma to the left and the right.
(?<!,)\b[0-9]+(?:,[0-9]+)?\b(?!,)
If the numbers are the only string, you can use anchors to assert the start and the end of the string.
^\d+(?:\,\d+)?$
Upvotes: 1
Reputation: 31
try this : \b\d+,\d+\b
with this expression all the matches will contain only one coma but the coma is not optional in this case.
Upvotes: 0
Reputation: 89639
You can use this pattern to test a full string:
^[0-9]+,?[0-9]*\b$
Here, the comma is optional, but since the "last" digits are optional too, I added a word boundary to ensure that the comma doesn't end the string. (a word boundary fails between a comma and the end of the string.)
Upvotes: 1