I don't have an experience on Regular Expressions. I need to a regular expression which doesn't allow to repeat of special characters (+-*/& etc.) The string can contain digits, alphanumerics, and special characters.
This should be valid : abc,df
This should be invalid : abc-,df
i will be really appreciated if you can help me ! Thanks for advance.
Two solutions presented so far match a string that is not allowed.
But the tilte is How to prevent..., so I assume that the regex should match the allowed string. It means that the regex should:
You can achieve this putting together the following parts:
^
- start of string anchor,(?!.*[...]{2})
- a negative lookahead for 2 consecutive special
characters (marked here as ...
), in any place,$
- end of string anchor.So the whole regex should be:
^(?!.*[!@#$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2}).+$
Note that within a char class (between [
and ]
) a backslash
escaping the following char should be placed before -
(if in
the middle of the sequence), closing square bracket,
a backslash itself and /
(regex terminator).
Or if you want to apply the regex to individual words (not the whole string), then the regex should be:
\b(?!\S*[!@#$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2})\S+