1

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 : _______][__________

2
  • 1
    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. :) Commented Jan 10, 2017 at 12:30
  • 1
    Actually, | in the pattern was a bug. Removing it from the character class is not just an improvement, it is a fix. Commented Jan 10, 2017 at 12:35

1 Answer 1

8

You just need to escape the [ and ] inside a character class in a Java regex.

Also, you do not need to put | as alternation symbol in the character class as it is treated as a literal |.

System.out.println(" &!)(}{][^\"~*?:;\\+-".replaceAll("[\\]\\[ &!)(}{^\"~*?:;\\\\+-]", "_"));
// => ___________________

See the Java demo


†: Note that in PCRE/Python/.NET, POSIX, you do not have to escape square brackets in the character class if you put them at the right places: []ab[]. In JavaScript, you always have to escape ]: /[^\]abc[]/. In Java and ICU regexps, you must always escape both [ and ] inside the character class. – Wiktor Stribiżew Jan 10 '17 at 12:39

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.