regexregex-lookarounds

Regex Length issue


I'm trying to build a regex where it accepts domain names with the following conditions:

  1. Allows DNS names (only hyphens, periods and alphanumeric characters allowed) upto 255 characters.
  2. Hyphens can only appear in between letters
  3. Should start with a letter and end with a letter. It will have minimum 3 characters (letters and periods mandatory, hyphen is optional.)
  4. The length of the label before a period should be 63

Possible Cases:

  1. a.b.c
  2. a-a.b

Cases that should not pass

  1. a-.b
  2. qwertqwertqwertqwertqwertqwertqwertqwertqwertqwertqwertqwertqwerhhg.v
  3. aaaa
  4. aaa-a

What I have built looks like this:

^(([a-zA-z0-9][A-Z0-9a-z-]{1,61}[a-zA-Z0-9][.])+[a-zA-Z0-9]+)$

But this does not accept a.b.c


Solution

  • You may use

    ^(?=.{1,255}$)(?=[^.]{1,63}(?![^.]))[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*(?:[.](?=[^.]{1,63}(?![^.]))[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)+(?:[.][a-zA-Z0-9-]*[a-zA-Z0-9])?$
    

    See the regex demo here.

    Pattern details