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 patt开发者_运维百科ern that I have or is there a version of replaceAll()
in another class which accepts a literal string instead of a pattern?
Just use String.replace(CharSequence,CharSequence)
rather than replaceAll
.
NB: replace
doesn't just replace the first occurrence, it replaces all occurrences, like replaceAll
.
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()
.
精彩评论