Home > Blockchain >  Regex for 2-30 characters plus any alphanumeric characters separated by a single hyphen
Regex for 2-30 characters plus any alphanumeric characters separated by a single hyphen

Time:01-03

I'm trying to come up with a regex for domain names that can either be 2-30 characters long with alphanumeric characters separated by a single hyphen with no other special characters allowed . something like this thisi67satest-mydomain

What I have at the moment is this : /^[a-z0-9-]{2,30}$/ but this doesn't cover all scenarios especially with respect to the single hyphen. I've always tried to google my way through these regexes. the above example will allow more than one hyphen which I don't want. How can i make the single hyphen mandatory?

CodePudding user response:

Try this:

^(?=.{2,30}$)[a-z0-9] -[a-z0-9] $
  • ^ the start of the line/string.
  • (?=.{2,30}$) ensures that the string between 2-30 characters.
  • [a-z0-9] one or more small letter or digit.
  • - one literal -.
  • [a-z0-9] one or more small letter or digit.
  • $ end of the line/string.

See regex demo

CodePudding user response:

I think following pattern will work for you. Let me know if it work.

(\w|-(?!-)){2,30}
  • Related