gpt4 book ai didi

java - 当字符串包含 [] 字符时替换字符串中的子字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:56:07 25 4
gpt4 key购买 nike

我想替换 substringin 字符串。例如:

localStringBuilder is for example "[sender] is xxxx xxxx xxx".

当我运行时

localStringBuilder.toString().replaceAll("[sender]", callerName);

无法正常工作。问题在于 [] 字符。如何解决?

最佳答案

只需使用 replace 代替 replaceAll

replaceAll 将 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);
}

输出:asdnew1123

关于java - 当字符串包含 [] 字符时替换字符串中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12184857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com