0

I struggle to change my current pattern:

^[\\\/0-9]{5,10}$

Which checks if input comprises of 5-10 numbers, slashes or backslashes. I would like to limit total slash and backslash count to two at most.

e.g. 12345/\\9 should not be valid after the change:

I tried dissecting them into a separate group like so ^([\\\/]{0,2}[0-9]){5,10}$ but am getting wrong matches.

ekad
  • 14,436
  • 26
  • 44
  • 46
zmaten
  • 429
  • 4
  • 16
  • Possible duplicate of [Regex matching if maximum two occurrences of dot and dash](https://stackoverflow.com/questions/6547187/regex-matching-if-maximum-two-occurrences-of-dot-and-dash) – Aran-Fey Feb 05 '18 at 01:09
  • Hmm, I just realized your problem is slightly different, because the question I linked counts dots and dashes separately. You'll have to make a small change to the regex from that answer: `^(?!.*?[\\\/].*[\\\/].*[\\\/]).*$` – Aran-Fey Feb 05 '18 at 01:12

2 Answers2

2

You can build a pattern using a lookahead anchored at the start of the string that tests one of the two "global conditions": the string length or number of slashes.

To limit the number of slashes you can design your pattern like this:

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

Then you only have to add the condition for the string length in the lookahead assertion (?=...):

^(?=.{5,10}$)[0-9]*(?:[/\\][0-9]*){0,2}$

(note that you have to escape the forward slash only if the pattern is delimited by slashes. Otherwise the slash isn't a special character.)

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
1

The following regular expression should do the job:

^(?=[^\\\/]*(?:[\\\/][^\\\/]*){0,2}$)[\d\\\/]{5,10}$

Visit this link to try a working demo.

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98