2

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?

Amal K
  • 4,359
  • 2
  • 22
  • 44
carrotcakeslayer
  • 809
  • 2
  • 9
  • 33
  • 1
    I guess a very common construct would be to use a non-capture group n-times. Something like `^\d\d?(?:-\d\d?){2}$` – JvdV Jun 18 '21 at 08:19
  • 1
    Thank you! It works at first try. I got to this "^(?:[\\d]{1,2}-?){3}" (or this which works with PCRE "^(?:[\\d]{1,2}+-?){3}" before asking for help but it fails and I don't understand why while yours works perfect. Would you mind helping me understand please? – carrotcakeslayer Jun 18 '21 at 08:30
  • 1
    I'd advise against that (your attempt) construct since you make the hyphen optional, essentially allowing for a string like "123" or "123456" to also be valid. Secondly, your character-class construct is better written like `\d` which is shorthand for digits ranging 0-9. Not sure why you tried to escape the backslash either. Maybe that is related to kupernetes which I don't know nothing about =) – JvdV Jun 18 '21 at 08:39
  • Yes, the escaped `\d` was the only way I was able to make it work with this helm chart rendering for kubernetes. Thank you very much for the explanation!!! – carrotcakeslayer Jun 18 '21 at 09:05

1 Answers1

2

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.

JvdV
  • 70,606
  • 8
  • 39
  • 70