Niranjan Kumar
Niranjan Kumar

Reputation: 1518

Using square brackets inside character class in Java regex

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

Upvotes: 1

Views: 2015

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

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

Upvotes: 8

Related Questions