Home > Software engineering >  Regex to allow only numbers and only one comma (not prefix or postfix comma)
Regex to allow only numbers and only one comma (not prefix or postfix comma)

Time:12-02

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?

CodePudding user response:

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.)

CodePudding user response:

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

CodePudding user response:

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.

  • Related