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?
-
possible duplicate of Backslash problem with String.replaceAllMcDowell– McDowell2011-05-26 08:40:50 +00:00Commented May 26, 2011 at 8:40
Add a comment
|
2 Answers
Just use String.replace(CharSequence,CharSequence) rather than replaceAll.
NB: replace doesn't just replace the first occurrence, it replaces all occurrences, like replaceAll.
7 Comments
Magic Octopus Urn
This doesn't just replace the first? Weird they called it "replaceAll" instead of "replaceRegex".
Thiago Mata
System.out.println("hello world, hello life, hello you".replace("hello","hi")); returns "hi world, hi life, hi you".Jon Skeet
@MagicOctopusUrn: Yes, I agree it was very poor naming - it's caused a lot of confusion over time.
Stunner
very bad naming of the methods. Why do they(sun/oracle) make simple things complicated
JohnRDOrazio
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). |
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
Julien Lafont
Works perfectly if you havea "$" in your matchingStr for example.
Pavlo Zvarych
rather Pattern.compile(); Pattern.quote() brings undesirable results
Mark Peters
@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.Pavlo Zvarych
@MarkPeters it was something like \\G1\\G for "$1"
Mark Peters
@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. |