java - 获取“当尝试替换字符串中的字符时

标签 java regex string replaceall

<分区>

我想用 ^ 替换字符串中的 "

String str = "hello \"there";
System.out.println(str);
String str1 = str.replaceAll("\"", "^");
System.out.println(str1);
String str2= str1.replaceAll("^", "\"");
System.out.println(str2);

输出是:

hello "there
hello ^there
"hello ^there

为什么我在字符串的开头得到额外的 " 而在字符串之间得到 ^

我期待:

hello "there

最佳答案

replaceAll()方法使用正则表达式作为第一个参数。

String str2= str1.replaceAll("^", "\""); 中的 ^ 将匹配字符串中的起始位置。 所以如果你想要 ^ 字符,写 \^

希望这段代码能帮到你:

String str2= str1.replaceAll("\\^", "\"");

关于java - 获取“当尝试替换字符串中的字符时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49513773/

相关文章:

java - 我如何从这样的数据库中检索数据?

java - Log4j 未使用属性文件找到自定义附加程序

html - 为什么 Visual Studio 警告未终止的字符串常量

c - 使用指针的段错误(核心转储)

java - 写入长值以在 apache POI 中表现出色

java - Hibernate - 从模式创建类

php - htaccess 重写,如果 url 扩展名是 .php 删除它

java - 正则表达式忽略字符串的一部分 - Java

regex - Perl 一次完成多个模式匹配和替换

java - 文字被截断?