David Gard
David Gard

Reputation: 12047

RegEx failing for strings with less than 3 characters

I am using a RegEx to test if a string is valid. The string must start and end with a number ([0-9]), but can contain comma's within.

I came up with this example, but it fails for strings less than 3 characters (for example 1 or 15 are as valid as 1,8). Presumably this is because I am specifically testing for a first and last character, but I don't know any other way of doing this.

How can I change this RegEx to match my requirements. Thanks.

^[0-9]+[0-9\,]+[0-9]$

Upvotes: 1

Views: 186

Answers (3)

DPM
DPM

Reputation: 1581

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

should work.

Always have one or more digits at the start, optionally followed by any number of comma-separated other groups of one or more digits.

If you allow commas next to each other, then the second + should be a *, I think.

Upvotes: 1

Smern
Smern

Reputation: 19066

Use this:

^[0-9]+(,[0-9])?$

the ,[0-9] part will be optional

visualized:

enter image description here

if you want allow for multiple comma-number groups... then replace the ? with *.

if you want to allow groups of numbers after the comma (which didn't seem to be the case in your example), then you should put + after that number group as well.

if both of the above mentioned are desired, your final regex could look like this:

^[0-9]+(,[0-9]+)*$

enter image description here

Upvotes: 3

C.B.
C.B.

Reputation: 8326

I would say the regex

\d(,?\d)*

Should satisfy for 1 or more digits that can be separated by only one comma. Note, 1,,2 fails

Upvotes: 0

Related Questions