Giovanni Far
Giovanni Far

Reputation: 1653

How to build a custom regex that matches dashes/alphanumeric characters and '.' dot characters that are not consecutive?

I need to build a regex that doesn't match the words with this requirements:

  1. at least 3 characters
  2. maximum 32 characters
  3. only a-z0-9_-.
  4. dots: . ok, .. nope

this is what i did:

/[0-9a-zA-Z\-\_\.]{3,32}/

the problem is that i can insert more than one . and i don't know how to fix it.

Upvotes: 1

Views: 58

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241278

You could use the following expression:

/(?:[\w-]|\.(?!\.)){3,32}/

Explanation:

  • (?: - Start of a non-capturing group
  • [\w-] - Character set to match [a-zA-Z0-9_-]
  • | - Alternation, or..
  • \.(?!\.) - Negative lookahead to match a . character literally if it isn't followed by another . character.
  • ) - Close the non-capturing group
  • {3,32} - Match the group 3 to 32 times

You may also want to add anchors if you want to match the entire string against the expression:

/^(?:[\w-]|\.(?!\.)){3,32}$/

Upvotes: 3

Related Questions