Replace “^” char

北城余情 提交于 2019-12-11 00:26:05

问题


I'm trying to replace the "^" character on a String using:

String text = text.replaceAll("^", "put this text");

If text as the following value:

"x^my string"

The resulting String is:

"put this textx^my string"

This only happens in case of the ^ character

Why is this?


回答1:


Just use the non-regex version String.replace() instead of String.replaceAll():

text = text.replace("^", "put this text");



回答2:


replaceAll expects a regexp as a first parameter. You need to escape it:

text = text.replaceAll("\\^", "put this text");

As for the why, the ^ expreg matches empty strings at the beginning of the parsed string. Then, replaceAll replaces this empty string with put this text. Which, in effect, is similar as putting put this text at the beginning of your original string.




回答3:


^ denotes the beginning of a line in a regular expression. You need to escape it:

String text = text.replaceAll("\\^", "put this text");



回答4:


^ indicates the beginning of the string.




回答5:


^ is a regular expression character which matches the start of a string. You need to escape it like:

text = text.replaceAll("\\^", "put this text");

Details are on the JavaDoc of java.util.regex.Pattern




回答6:


The symbol ^ matches the beginning of a line. If you want to match the caracter ^ you have to escape it

String text = text.replaceAll("\^", "put this text");


来源:https://stackoverflow.com/questions/6666947/replace-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!