Waqar Ahmed
Waqar Ahmed

Reputation: 1444

Regular Expression for not allowing two consecutive special characters

What i am trying to do is to not allow two consecutive special characters like &* or *$ or &&, but it should allow special characters in between strings like Hello%Mr&.

What i have tried so far:

^(([\%\/\\\&\?\,\'\;\:\!\-])\2?(?!\2))+$

Upvotes: 3

Views: 9901

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can use this kind of pattern:

\A\W?(?>\w+\W)*\w*\z

or

\A[%/\\&?,';:!-]?(?>[^%/\\&?,';:!-]+[%/\\&?,';:!-])*[^%/\\&?,';:!-]*\z

or

\A[^\p{L}\p{N}\s]?(?>[\p{L}\p{N}\s]+[^\p{L}\p{N}\s])*[\p{L}\p{N}\s]*\z

or

\A[^a-zA-Z0-9 ]?(?>[a-zA-Z0-9 ]+...

depending of what do you call a "special character".

Upvotes: 0

ndnenkov
ndnenkov

Reputation: 36101

^(?!.*[\%\/\\\&\?\,\'\;\:\!\-]{2}).*$

The idea is to use a negative lookahead ((?!)) to verify that nowhere in the string (.*) are there two consecutive "special" characters ([...]{2}). Afterwards, you just match the entire string (.*).

Upvotes: 11

Related Questions