Java 当字符串包含[]个字符时,替换字符串中的子字符串
我想替换字符串中的子字符串。 例如:Java 当字符串包含[]个字符时,替换字符串中的子字符串,java,Java,我想替换字符串中的子字符串。 例如: localStringBuilder is for example "[sender] is xxxx xxxx xxx". 当我跑的时候 localStringBuilder.toString().replaceAll("[sender]", callerName); 工作不正常。问题包含[]字符。如何解决这个问题?只需使用replace代替replaceAll replaceAll将REGEX作为输入,不是字符串,而是REGEX[]是用于对表达式进行
localStringBuilder is for example "[sender] is xxxx xxxx xxx".
当我跑的时候
localStringBuilder.toString().replaceAll("[sender]", callerName);
工作不正常。问题包含
[]
字符。如何解决这个问题?只需使用replace
代替replaceAll
replaceAll
将REGEX作为输入,不是字符串,而是REGEX<代码>[]是用于对表达式进行分组的正则表达式的重要部分
localStringBuilder.toString().replace(“[sender]”,callerName)
将像您期望的那样工作,因为它将普通字符串作为两个参数
是相同的。当字符串中没有[]个字符时工作
–@mbrc 1分钟前
不正确,我已经测试了它:
public static void main(String[] args) {
String s = "asd[something]123";
String replace = s.replace("[something]", "new1");
System.out.println(replace);
}
输出:asdnew1123replaceAll返回一个包含替换内容的新字符串。它不会替换原始字符串中的字符 字符串newString=localStringBuilder.toString().replaceAll(“[sender]”,callerName) 用这个
localStringBuilder.toString().replaceAll("\\[sender\\]", callerName);
这是有效的:
locaStringBuilder.toString().replaceAll("\\[sender\\]", callerName);
是一样的。在中没有[]个字符时工作string@mbrc,没问题。我不得不说这有点悲哀,在所有这些答案中,只有我建议在这里使用
replace
。您的问题并不是使用正则表达式的错误方式,但只是在您可能不想使用的情况下使用它:)添加“\”不会使您的代码变得更好,它只是一种解决问题的方法,而这个问题本来就不应该发生。如果[sender]是常量,而我不能使用\\?或者您可以像其他人提到的那样使用,char)怎么办