Skip to content
Advertisement

Regular Expression for not allowing two consecutive special characters and also not in beginning and end

I’m looking for a regex for a string to

  1. Contain only A-Z a-z 0-9 _ – .
  2. Not begin/end with _ – .
  3. Not containing consecutive special characters or their combination
  4. Max 36 length, minimum 1

Right

abcd-efgH
1
a
123
abc
abc-asd-123-asd_asd.asd

Wrong:

-
abc-_asd
abc.
abc.-asd
123123-123123-ads--asd
091-asdsad---

I seearched around and got this :-

/^(?!.*[^na-z0-9]{2})(?=.*[a-z0-9]$)[a-z0-9].*$/gim

but this allows all special characters and not just the 3 that i checek

Advertisement

Answer

You may use this regex with 3 lookaheads:

^(?![-_.])(?!.*[-_.]{2})(?!.*[-_.]$)[-w.]{1,36}$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?![-_.]): Negative lookahead to disallow [-_.] at the start
  • (?!.*[-_.]{2}): Negative lookahead to disallow 2 consecutive [-_.] anywhere
  • (?!.*[-_.]$): Negative lookahead to disallow [-_.] at the end
  • [-w.]{1,36}: Match a [-a-zA-Z0-9_.] character, min: 1, max: 36
  • $: End
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement