我正在尝试使用以下命令替换String上的“^”字符:
String text = text.replaceAll("^", "put this text");
如果text为以下值:
"x^my string"
结果字符串是:
"put this textx^my string"
仅在^
字符
为什么会这样?
答案 0 :(得分:9)
只需使用非正则表达式String.replace()
而不是String.replaceAll()
:
text = text.replace("^", "put this text");
答案 1 :(得分:5)
replaceAll
期望将regexp作为第一个参数。你需要逃脱它:
text = text.replaceAll("\\^", "put this text");
至于原因,^
expreg匹配解析字符串开头的空字符串。然后,replaceAll
将此空字符串替换为put this text
。实际上,这与将put this text
放在原始字符串的开头类似。
答案 2 :(得分:1)
^
表示正则表达式中一行的开头。你需要逃脱它:
String text = text.replaceAll("\\^", "put this text");
答案 3 :(得分:0)
^
表示字符串的开头。
答案 4 :(得分:0)
^
是一个正则表达式字符,它匹配字符串的 start 。你需要像以下一样逃避:
text = text.replaceAll("\\^", "put this text");
的JavaDoc的详细信息
答案 5 :(得分:0)
符号^匹配行的开头。如果你想匹配caracter ^你必须逃避它
String text = text.replaceAll("\^", "put this text");