[java] Regular expression include and exclude special characters

I'm finding a regular expression which adheres below rules.

Allowed Characters

Alphabet : a-z / A-Z
Numbers : 0-9
Special Characters : ~ @ # $ ^ & * ( ) - _ + = [ ] { } | \ , . ? :
(spaces should be allowed)

Not Allowed

Special Characters : < > ' " / ; ` %

This question is related to java regex

The answer is


[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*

This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.


You haven't actually asked a question, but assuming you have one, this could be your answer...

Assuming all characters, except the "Special Characters" are allowed you can write

String regex = "^[^<>'\"/;`%]*$";