Below is the regex I have written to replace the special chars &!)(}{][^"~*?:;\+- from a string, but somehow it is not able to replace [ & ] from it as it acts as beginning and closing of regex. How can I do that?
System.out.println(" &!)(}{][^\"~*?:;\\+-".replaceAll("[| |&|!|)|(|}|{|^|\"|~|*|?|:|;|\\\\|+|-]", "_"));
}
The output for now : _______][__________
System.out.println(" &!)(}{][^\"~*?:;\\+-".replaceAll("[\\[\\] &!)(}{^\"~*?:;\\\\+-]", "_"));Here is your code improved a bit, no need for all the|'s. The way to go is to escape the brackets. you do that by puting a` before it, but in the case of java you need to escape the` itself therefore you put two ``'s before the bracket. :)|in the pattern was a bug. Removing it from the character class is not just an improvement, it is a fix.