jasiu
jasiu

Reputation: 73

Regex - no consecutive special chars

I'm trying to write a Regex with these requirements:

Example: I'm #1! I feel greaaaat! (OK), I''m kinda .{}. sad (NOT OK)

Example: a.a,aaa (OK), a.a,a[]a/ (NOT OK)

I've written this Regex so far, but it seems to be not working properly.

/^(?!.*?[!"#$%&'()*+,-./:;<=>?@[]^_`{|}~]{2})[A-Za-z0-9!"#$%&'()*+,-./:;<=>?@[]^_`{|}~].*$/

Can you suggest any solution? Thanks.

Upvotes: 2

Views: 621

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You can use

/^(?!.*[!-\/:-@[-`{-~]{2})[A-Za-z0-9 ]*(?:[!-\/:-@[-`{-~][A-Za-z0-9 ]*){0,4}$/

See the regex demo.

Details

  • ^ - start of string
  • (?!.*[!-\/:-@[-`{-~]{2}) - no two consecutive ASCII punctuation after any zero or more chars other than line break chars, as many as possible
  • [A-Za-z0-9 ]* - zero or more letters, digits or spaces
  • (?:[!-\/:-@[-`{-~][A-Za-z0-9 ]*){0,4} - zero to four occurrences of
    • [!-\/:-@[-`{-~] - a single ASCII punctuation char
    • [A-Za-z0-9 ]* - zero or more letters, digits or spaces
  • $ - end of string.

Upvotes: 1

Related Questions