George
George

Reputation: 1191

Regex 2 digits separated by commas, not all required

I need a regex for the following input:

[2 digits], comma, [two digits], comma, [two digits]

The 2 digits cannot start with 0. It is allowed to only enter the first 2 digits. Or to enter the first 2 digits, then a comma en then the next 2 digits. Or to enter the full string as described above.

Valid input would be:

10
99
17,56
15,99
10,57,61
32,44,99

Could anyone please help me with this regex?

At the moment I have this regex, but it doesn't limit the input to maximum 3 groups of 2 digits:

^\d{2}(?:[,]\d{2})*$

Upvotes: 2

Views: 5929

Answers (2)

stefita
stefita

Reputation: 1793

^[1-9]\d(?:,[1-9]\d){0,2}$

The first part ([1-9]\d) is simply the first number, which has to be present at all times. It consists of a non-zero digit and an arbitrary second digit (\d).

What follows is a non-capturing group ((?:...)), containing a comma followed by another two-digit number (,[1-9]\d), just alike the first one. This group can be repeated between zero and two times ({0,2}), so you get either no, one or two sequences of a comma and another number.

You can easily expand the part in the curly braces to allow for more allowed numbers.

Upvotes: 13

dstibbe
dstibbe

Reputation: 1697

^[1-9]\d([,][1-9]\d){0,2}$

Upvotes: 1

Related Questions