尝试替换字符串中的字符时获取 "
Getting " when trying to replace a character in string
我想用 ^
.
替换字符串中的 "
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()
方法使用正则表达式作为第一个参数。
^
in String str2= str1.replaceAll("^", "\"");
将匹配字符串中的起始位置。
所以如果你想要 ^
字符,写 \^
希望这段代码能帮到你:
String str2= str1.replaceAll("\^", "\"");
^
表示正则表达式中一行的开始,你可以在它之前添加两个\
:
String str2= str1.replaceAll("\^", "\"");
第一个用于编译转义,第二个用于正则表达式转义
尝试使用不使用正则表达式的 replace
String str2 = str1.replace("^", "\"");
为什么要使用replaceAll。有什么具体原因吗?
如果您可以使用替换功能,请尝试以下
String str2= str1.replace("^", "\"");
由于 String::replaceAll 使用正则表达式,您需要先将搜索和替换字符串转换为正则表达式:
str.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("^"));
我想用 ^
.
"
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()
方法使用正则表达式作为第一个参数。
^
in String str2= str1.replaceAll("^", "\"");
将匹配字符串中的起始位置。
所以如果你想要 ^
字符,写 \^
希望这段代码能帮到你:
String str2= str1.replaceAll("\^", "\"");
^
表示正则表达式中一行的开始,你可以在它之前添加两个\
:
String str2= str1.replaceAll("\^", "\"");
第一个用于编译转义,第二个用于正则表达式转义
尝试使用不使用正则表达式的 replace
String str2 = str1.replace("^", "\"");
为什么要使用replaceAll。有什么具体原因吗?
如果您可以使用替换功能,请尝试以下
String str2= str1.replace("^", "\"");
由于 String::replaceAll 使用正则表达式,您需要先将搜索和替换字符串转换为正则表达式:
str.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("^"));