Daniel Birowsky Popeski
Daniel Birowsky Popeski

Reputation: 9286

Quantifier not working

I'm bad at regex. Just bad. I thought I was decent, but no. I'm just bad.

With that out of my chest, how do we make the {1,61} quantifier work on the whole preceding group?

^((xn-|[a-zA-Z0-9]+)((-[a-zA-Z0-9]+)+)?){1,61}(\.[a-zA-Z]{2,})?$

Here's the RegExr.

This is a domain name pattern by the way.

Upvotes: 1

Views: 76

Answers (1)

Raman
Raman

Reputation: 19585

Your expression is not working because the {1-61} applies to the previous group, which itself consists of 1 or more characters.

Here is the answer using a positive lookahead as commented by @Casimir:

^(?=.{1,61}$)((xn-|[a-zA-Z0-9]+)((-[a-zA-Z0-9]+)+)?)(\.[a-zA-Z]{2,})?$

Note that if you are trying to match domain names, you really should be matching a max of 63 characters in the name, not including the dot-tld. The expression above will match max 61 of the entire name, including the dot-tld, so it will disallow valid names. Perhaps this is closer to what you want:

^(?=[^\.]{1,63}\.)(xn-|[a-zA-Z0-9]+)((-[a-zA-Z0-9]+)+)?(\.[a-zA-Z]{2,})?$

Upvotes: 2

Related Questions