Reputation: 2281
I am new to writing regular expressions. I am planning to write regular expression for validating wild card domain matching. Here are scenarios.
Correct:
*.test.com
test.com
abc.test.com
Incorrect:
*test.com
test.com*
test.*.com
test.abc*.com
Here is my regular expression for above secnario
/^(([a-zA-Z0-9]|\*\.[a-zA-Z0-9])([a-zA-Z0-9\-_]{0,243}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/
It is working as expected. can we improve or write better expression?
Upvotes: 0
Views: 6660
Reputation: 6891
^(\*\.)?([\w-]+\.)+[\w-]+$
matches your examples. Demo 1
From my point of view i would also treat the third negative example as correct.
^(([\w-]+\.)|(\*\.))+[\w-]+$
edit:
you may have to adapt the character classes to contains all allowed characters. I wanted to keep the regex easy to read
Upvotes: 2