问题
I am using a backslash as an escape character for a serialization format I am working on. I have it as a constant but IntelliJ is underlining it and highlighting it red. On hover it gives no error messages or any information as to why it does not like it.
What is the reason for this and how do I fix it?
回答1:
IntelliJ is smarter than I am and realised that I was using this character in a regular expression where 2 backslashes would be needed, however, IntelliJ also assumed that my puny mind could find the problem without giving me any information about it.
回答2:
If it's being used as a regular expression, then the "\" must be escaped.
If you're escaping a "\" as "\" like traditional regular expressions require, then you also need to add two more \\
for a total of \\\\
.
This is because of the way Java interprets "\":
In literal Java strings the backslash is an escape character. The literal string "\" is a single backslash. In regular expressions, the backslash is also an escape character. The regular expression \ matches a single backslash. This regular expression as a Java string, becomes "\\". That's right: 4 backslashes to match a single one.
The regex \w matches a word character. As a Java string, this is written as "\w".
The same backslash-mess occurs when providing replacement strings for methods like String.replaceAll() as literal Java strings in your Java code. In the replacement text, a dollar sign must be encoded as \$ and a backslash as \ when you want to replace the regex match with an actual dollar sign or backslash. However, backslashes must also be escaped in literal Java strings. So a single dollar sign in the replacement text becomes "\$" when written as a literal Java string. The single backslash becomes "\\". Right again: 4 backslashes to insert a single one.
来源:https://stackoverflow.com/questions/27618325/underlined-backslash-intellij