问题
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