Jammy Jammy - 8 months ago 59
Java Question

Java replacing special characters

I'm trying to replace special characters in a file with a pattern with only special characters, but it doesn't seem to be working.

String special = "Something @$ great @$ that.";
special = special.replaceAll("@$", "as");

However, when I run that I get the original string instead of the replaced string. What am I doing wrong?


Simply use String#replace(CharSequence target, CharSequence replacement) in your case to replace a given CharSequence, as next:

special = special.replace("@$", "as");

Or use Pattern.quote(String s) to convert your String as a literal pattern String, as next:

special = special.replaceAll(Pattern.quote("@$"), "as");

If you intend to do it very frequently, consider reusing the corresponding Pattern instance (the class Pattern is thread-safe which means that you can share instances of this class) to avoid compiling your regular expression at each call which has a price in term of performances.

So your code could be:

private static final Pattern PATTERN = Pattern.compile("@$", Pattern.LITERAL);
special = PATTERN.matcher(special).replaceAll("as");