Java 没有正则表达式的 String.replaceAll
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4316710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String.replaceAll without RegEx
提问by dromodel
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?
我想替换字符串中子字符串的所有实例,但String.replaceAll()
只接受一个模式。我来自上一场比赛的字符串。是否可以将转义添加到我拥有的模式中,或者replaceAll()
在另一个类中是否有接受文字字符串而不是模式的版本?
采纳答案by Jon Skeet
Just use String.replace(CharSequence,CharSequence)
rather than replaceAll
.
只需使用String.replace(CharSequence,CharSequence)
而不是replaceAll
.
回答by Mark Peters
The method to add escapes is Pattern.quote()
.
添加转义符的方法是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 alloccurrences just like replaceAll()
.
但正如乔恩所说,你可以只使用replace()
. 尽管它偏离了replaceAll
名称,但它确实替换了所有出现的内容,就像replaceAll()
.