在尝试替换字符串中的字符时获取"

Kum*_*rsh 8 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);
Run Code Online (Sandbox Code Playgroud)

输出是:

hello "there
hello ^there
"hello ^there
Run Code Online (Sandbox Code Playgroud)

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

我期待:

hello "there
Run Code Online (Sandbox Code Playgroud)

ton*_*oan 8

replaceAll()方法使用第一个参数的正则表达式.

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

希望这段代码可以帮助:

String str2= str1.replaceAll("\\^", "\"");
Run Code Online (Sandbox Code Playgroud)


Rei*_*eus 5

尝试使用replace哪些不使用正则表达式

String str2 = str1.replace("^", "\"");
Run Code Online (Sandbox Code Playgroud)