String.replaceAll without RegEx

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

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

Solution 2 - Java

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().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondromodelView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaMark PetersView Answer on Stackoverflow