When I try:
Pattern p = Pattern.compile("[,.s;:{}/[]<>?`~!@#$%^&*()_+=]");
my program bugs out. Why doesn't it like this?
When I try:
Pattern p = Pattern.compile("[,.s;:{}/[]<>?`~!@#$%^&*()_+=]");
my program bugs out. Why doesn't it like this?
This regular expression won't compile because in Java you need to escape square brackets [, ] when you use them inside character classes:
Pattern p = Pattern.compile("[,.s;:{}/\\[\\]<>?`~!@#$%^&*()_+=]");
^^^^^^
The double escape \\ is needed because slashes \ are used in Java strings to escape special sequences like \n, \r ... etc
Now how do we include a literal slash in a Java string when we need one if it is used to escape stuff ?
We escape it using it self thus typing it twice \\.
Why do we need to escape [ and ] inside character classes ?
Because Java supports character class subtraction, intersection and union, for example:
[a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]] d, e, or f (intersection)
[a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)
Examples are taken from the documentation.
You need to escape special characters such as [, ], +, (, ) etc. I'm not 100% sure but you might be able to use \Q and \E to tell the regex to treat the special chars as literals.
Eg:
Pattern p = Pattern.compile("[\\Q,.s;:{}/[]<>?`~!@#$%^&*()_+=\\E]");
See the Quotation section in the javadoc
[\\Q\\[\\]\\E] escaping [ and ] is incorrect because it will make \, [, \, ] literals in character class and OP don't want to include \ in this class.This is correct regex:
Pattern p = Pattern.compile("[,.s;:{}/\\[\\]<>?`~!@#$%^&*()_+=]");
You need to escape [ and ]
OR this will also work:
Pattern p = Pattern.compile("[],.s;:{}/\\[<>?`~!@#$%^&*()_+=]");
With only [ needs to be escaped.
] can avoid escaping if it is at first position inside character class.
As already said, you have to skip the special characters ...
In order to do that I will suggest you to use the Pattern.quote method (see here as a reference).
String s = Pattern.quote("[,.s;:{}/[]<>?`~!@#$%^&*()_+=]");
Pattern p = Pattern.compile(s);