149

I'd like to replace all instances of a substring in a string but String.replaceAll() only accepts a pattern. The string that I have came from a previous match. Is it possible to add escapes to the pattern that I have or is there a version of replaceAll() in another class which accepts a literal string instead of a pattern?

1

2 Answers 2

242

Just use String.replace(CharSequence,CharSequence) rather than replaceAll.

NB: replace doesn't just replace the first occurrence, it replaces all occurrences, like replaceAll.

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

7 Comments

This doesn't just replace the first? Weird they called it "replaceAll" instead of "replaceRegex".
System.out.println("hello world, hello life, hello you".replace("hello","hi")); returns "hi world, hi life, hi you".
@MagicOctopusUrn: Yes, I agree it was very poor naming - it's caused a lot of confusion over time.
very bad naming of the methods. Why do they(sun/oracle) make simple things complicated
I believe the naming of replaceAll (regex method) was to differentiate from replaceFirst (regex method), not so much to differentiate from replace (non regex method).
|
107

The method to add escapes is Pattern.quote().

String replaced = myString.replaceAll(Pattern.quote(matchingStr), replacementStr)

But as Jon says you can just use replace(). Despite the fact that it deviates from the replaceAll name, it does replace all occurrences just like replaceAll().

8 Comments

Works perfectly if you havea "$" in your matchingStr for example.
rather Pattern.compile(); Pattern.quote() brings undesirable results
@PavloZvarych: Pattern.compile() compiles the string as a regular expression, meaning the special characters will be given the special meaning. That's the complete opposite of what Pattern.quote() does, and what the OP was asking for (quote() says, "treat the string as a literal"). Maybe you could expand on what "undesirable results" you're talking about.
@MarkPeters it was something like \\G1\\G for "$1"
@PavloZvarych: If you're trying to quote the replacement (and not the search pattern), you want to use Matcher.quoteReplacement("$aa +"). Pattern.compile() produces a Pattern, not a String, so it's unclear to me how you are even using it in replaceAll.
|

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.