简体   繁体   中英

String.replaceAll without RegEx

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM