开发者

String.replaceAll without RegEx

开发者 https://www.devze.com 2023-01-27 10:26 出处:网络
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 pa

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

0

精彩评论

暂无评论...
验证码 换一张
取 消