Error in regex to catch special characters
i wrote a regular expression to catch special characters in an input string but it catches the numbers as well. Here is the regex,
final String REGEX="[^.,%*$#@?^<!&>'|/\\\\~\\[\\]{}+-=\"]*";
I need to catch the above mentioned characters only. Please help me.
You created a range with the unescaped hyphen.
The misplaced hyphen makes the pattern match these characters:
Escape the hyphen or place at the end of the class:
final String REGEX="[^.,%*$#@?^<!&>'|/\\\\~\\[\\]{}+=\"-]*";
^
Here is this regex demo
Move the hyphen (-
) to the end of your character class:
final String REGEX="[^.,%*$#@?^<!&>'|/\\\\~\\[\\]{}+=\"-]*"
Where it's currently positioned (+-=
), it expresses a range from +
to =
. This range includes, a.o. all digits.