Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ says "\\" (match on single backslash) is an illegal / unsupported escape sequence for Pattern.compile

The following pattern compile expression gives error in IntelliJ, even though the expression compiles and works well in Java (1.8):

Pattern.compile("\\", Pattern.LITERAL);

I´m using the following code to escape all occurences of \ in a String with a double \\, like this:

private final static Pattern BACKSLASH_PATTERN = Pattern.compile("\\", Pattern.LITERAL);
private final static String BACKSLASH_REPLACE = Matcher.quoteReplacement("\\\\");

private String escapeBackslashes(final String s) { 
    return BACKSLASH_PATTERN.matcher(s).replaceAll(BACKSLASH_REPLACE);
}

When using s.replace("\\", "\\\\") IntelliJ does not complain, though, but I need to use the precompiled pattern for performance reasons (100s of MBs of data to process).

Might be a bug as in IntelliJ says \b (backspace) is an illegal escape sequence inside a string literal. Why? ?

like image 517
Mauritz Løvgren Avatar asked Nov 27 '18 09:11

Mauritz Løvgren


1 Answers

You've got double escaping problems there. Java needs two backslashes \ in order for one backslash to appear in your string. Regex also has backslash escaping such that two backslashes in regex becomes one backslash for pattern matching.

Try escaping twice:

Pattern.compile("\\\\", Pattern.LITERAL);

This puts the pattern as '\' in regex which matches a single backspace.

like image 125
Kieveli Avatar answered Oct 17 '22 15:10

Kieveli