获得"当试图替换字符串中的字符时

时间:2018-03-27 13:09:39

标签: 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

5 个答案:

答案 0 :(得分:8)

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

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

希望此代码可以提供帮助:

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

答案 1 :(得分:5)

尝试使用不使用正则表达式的# Use PHP56 Single php.ini as default AddHandler application/x-httpd-php56s .php DirectoryIndex index.php RewriteEngine On RewriteCond %{SCRIPT_FILENAME} !-d RewriteCond %{SCRIPT_FILENAME} !-f RewriteRule ^ index.php [L] RewriteRule !^(public/|index\.php) [NC,F]

replace

答案 2 :(得分:3)

create表示在正则表达式中开始一行,您可以在它之前添加两个^

\

第一个用于转义进行编译,第二个用于转义正则表达式。

答案 3 :(得分:2)

由于String::replaceAll使用正则表达式,您需要先将搜索和替换字符串转换为正则表达式:

str.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("^"));

答案 4 :(得分:0)

为什么要使用replaceAll。有什么具体原因吗? 如果你可以使用替换功能,请尝试下面 String str2= str1.replace("^", "\"");