I'm trying to build a regex where it accepts domain names with the following conditions:
Possible Cases:
Cases that should not pass
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
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
^
- start of string(?=.{1,255}$)
- the whole string should have 1 to 255 chars(?=[^.]{1,63}(?![^.]))
- there must be 1 to 63 chars other than .
before the char other than .
or end of string[a-zA-Z0-9]+
- 1 or more alphanumeric chars(?:
- start of a non-capturing group:
-
- a hyphen[a-zA-Z0-9]+
- 1+ alphanumeric chars)*
- zero or more repetitions(?:
- start of a non-capturing group...
[.]
- a dot(?=[^.]{1,63}(?![^.]))
- there must be 1 to 63 chars other than .
before the char other than .
or end of string[a-zA-Z0-9]+
- 1+ alphanumeric chars(?:-[a-zA-Z0-9]+)*
- 0 or more repetitions of a -
followed with 1+ alphanumeric chars)+
-... 1 or more times(?:
- start of a non-capturing group...
[.]
- a dot[a-zA-Z0-9-]*
- 1+ alphanumeric or -
chars[a-zA-Z0-9]
- an alphanumeric char (no hyphens at the end))?
-... 1 or 0 times (it is optional)$
- end of string.