the sandman
the sandman

Reputation: 1029

Issue allowing new character to Regex

Current Regex:

^([\d-]*[A-z]?|[A-z]?[\d-]*|[\d-]*[A-z]?[\d-]*){3}$ 

(Allows a max of 3 letters and any amount of numbers or hyphens)

I want to also allow the forward slash(/) to be just like the hypen(-), where there can be no limit, but i am doing something wrong, it doesnt match the following sequence.

Updated Regex:

^([\d-]*[\d/]*[A-z]?|[A-z]?[\d-]*[\d/]*|[\d-]*[\d/]*[A-z]?[\d-]*[\d/]*){3}$

(Allows a max of 3 letters and any amount of numbers or hyphens or forward slashes)

Good: 1234-aAa/

Good: 1234/aAa-

Bad: 1234aAa/-

This only happens when i add a hyphen after the forward slash and 3 alpha letters, what is wrong with my updated regex? The order doesnt matter for any characters, its just to the total overall characters in the string. Thanks!

Upvotes: 0

Views: 45

Answers (1)

stema
stema

Reputation: 93026

Try this here

^(?=(?:[^a-z]*[a-z]){0,3}[^a-z]*$)[a-z0-9/-]*$

See and test it here on Regexr

I use only a-z and the IgnoreCase option because A-z is not [A-Za-z], there are some characters more inbetween.

So, basically my regex matches everything [a-z0-9/-]* I allow in the character class at the end.

This part (?=(?:[^a-z]*[a-z]){0,3}[^a-z]*$) is a positive lookahead, that ensures your requirement of max 3 letters. See here for more about lookaheads

Upvotes: 1

Related Questions