Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underlined backslash IntelliJ

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.

enter image description here

What is the reason for this and how do I fix it?

like image 802
user2248702 Avatar asked Dec 23 '14 10:12

user2248702


2 Answers

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.

like image 60
user2248702 Avatar answered Sep 28 '22 07:09

user2248702


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.

like image 37
Shawn Avatar answered Sep 28 '22 06:09

Shawn