tags:

views:

191

answers:

2

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})*$
+10  A: 
^[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.

stefita
+1 For not allowing leading zeros.
Gumbo
Thanks, it works. But could you please explain how it works exactly? And would it be possible to expand on my regex to make it work as required? ^\d{2}(?:[,]\d{2})*$
iar
@iar: You can use back-ticks in comments to format source-code.
soulmerge
I think iar wants this: `^[1-9]\d(?:,\d\d){0,2}$`
Nick D
Thank @Johannes Rössel for explaining my code. @iar I'm not sure what are exactly you asking.
stefita
@stefita: never mind, I asked to change the regex I came up with (in my question), to make it work as required.@Johannes Rössel: thans for the explanation.
iar
+1  A: 
^[1-9]\d([,][1-9]\d){0,2}$
You don't need `[]` around a single character. A single `,` is exactly the same as the character class `[,]`.
Joey
from experience I've found it better to be safe than sorry. Therefore I always use [] around special characters such as ',' '.' '$' '#' etc.
, - is not special character. Regular Expressions already is a hard to read/understand language, so adding unnecessary characters to already complicated expressions is bad idea. But +1 for working answer.
Kamarey