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

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Niranjan Kumar
  • 1,348
  • 11
  • 27
  • 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. :) – fill͡pant͡ Jan 10 '17 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. – Wiktor Stribiżew Jan 10 '17 at 12:35

1 Answers1

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

VimNing
  • 1,192
  • 4
  • 20
  • 47
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476