Reputation: 477
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.
Upvotes: 0
Views: 1370
Reputation: 89547
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.)
Upvotes: 2
Reputation: 23675
The following regular expression should do the job:
^(?=[^\\\/]*(?:[\\\/][^\\\/]*){0,2}$)[\d\\\/]{5,10}$
Visit this link to try a working demo.
Upvotes: 1