java 当字符串包含 [] 个字符时替换字符串中的子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12184857/
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
replace substring in string when string contains [] characters
提问by mbrc
I want to replace substringin string. For example:
我想替换 substringin 字符串。例如:
localStringBuilder is for example "[sender] is xxxx xxxx xxx".
and when I run
当我跑步时
localStringBuilder.toString().replaceAll("[sender]", callerName);
not working correctly. Prblem is with []
characters. How to solve this?
工作不正常。问题在于[]
字符。如何解决这个问题?
采纳答案by dantuch
Just use replace
in place of replaceAll
只用replace
代替replaceAll
replaceAll
take REGEX as input, not a String, but regex. []
are important parts of regexes using to group expressions.
replaceAll
将 REGEX 作为输入,不是字符串,而是正则表达式。[]
是正则表达式的重要组成部分,用于对表达式进行分组。
localStringBuilder.toString().replace("[sender]", callerName);
will work exaclty as you expect, because it takes normal Strings as both parameters.
localStringBuilder.toString().replace("[sender]", callerName);
将按照您的预期工作,因为它将普通字符串作为两个参数。
is the same. Works when is no [] characters in string
– @mbrc 1 min ago
is the same. Works when is no [] characters in string
– @mbrc 1 分钟前
not true, I've testedit:
不是真的,我已经测试过了:
public static void main(String[] args) {
String s = "asd[something]123";
String replace = s.replace("[something]", "new1");
System.out.println(replace);
}
output: asdnew1123
输出:asdnew1123
回答by DJClayworth
replaceAll returns a new string with the replacement. It doesn't replace the characters in the original string.
replaceAll 返回一个带有替换的新字符串。它不会替换原始字符串中的字符。
String newString = localStringBuilder.toString().replaceAll("[sender]", callerName);
String newString = localStringBuilder.toString().replaceAll("[sender]", callerName);
回答by Ransom Briggs
Use this
用这个
localStringBuilder.toString().replaceAll("\[sender\]", callerName);
回答by Dan D.
This works:
这有效:
locaStringBuilder.toString().replaceAll("\[sender\]", callerName);