BaldwinIV
BaldwinIV

Reputation: 147

Regex to allow only numbers and only one comma (not prefix or postfix comma)

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

Answers (3)

The fourth bird
The fourth bird

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(?!,)

Regex demo

If the numbers are the only string, you can use anchors to assert the start and the end of the string.

^\d+(?:\,\d+)?$

Regex demo

Upvotes: 1

Max Kelii
Max Kelii

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

Casimir et Hippolyte
Casimir et Hippolyte

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

Related Questions