To match these examples:
1-10-1
1-7-3
10-8-5
1-7-14
11-10-12
This regex works:
^[\\d]{1,2}-[\\d]{1,2}-[\\d]{1,2}$
How could this be written in a way that just matches something like "[\d]{1,2}-?
" three (n) times?
You may use:
^\d\d?(?:-\d\d?){2}$
See an online demo.
^
- Start line anchor.\d\d?
- A single digit followed by an optional one (the same as \d{1,2}
).(?:-\d\d?){2}
- A non-capture group starting with an hyphen followed by the same construct as above, one or two digits. The capture group is repeated exactly two times.$
- End string anchor.The idea here is to avoid an optional hyphen in the attempts you made since essentially you'd start to allow whole different things like "123" and "123456". It's more appropriate to match the first element of a delimited string and then use the non-capture group to match a delimiter and the rest of the required elements exactly n-1 times.