替换"^"char

Red*_*gle 2 java regex string character

我正在尝试使用以下命令替换String上的"^"字符:

String text = text.replaceAll("^", "put this text");
Run Code Online (Sandbox Code Playgroud)

如果文本为以下值:

"x^my string"
Run Code Online (Sandbox Code Playgroud)

生成的String是:

"put this textx^my string"
Run Code Online (Sandbox Code Playgroud)

这只发生在^角色的情况下

为什么是这样?

Sea*_*oyd 9

只需使用非正则表达式版本String.replace()而不是String.replaceAll():

text = text.replace("^", "put this text");
Run Code Online (Sandbox Code Playgroud)


Viv*_*sse 5

replaceAll期望正则表达式作为第一个参数.你需要逃脱它:

text = text.replaceAll("\\^", "put this text");
Run Code Online (Sandbox Code Playgroud)

至于原因,^expreg在解析字符串的开头匹配空字符串.然后,replaceAll用这个空字符串替换put this text.实际上,这与放在put this text原始字符串的开头类似.