Redundant Character Escape ‘\/‘ in RegExp

正则表达式的转义字符反斜杠 \总是不好理解,因为字符串本身会先转义一次。

上面的Android Studio的经过意思是说在正则表达式中使用 ‘\\/‘ 是多余的,因为字符串 “\\/”转义之后是 \/ ,而正则表达式匹配的时候 \/ 等价于 /

Matching Characters

如果需要匹配字符 \ 这两个字符 ,标准的匹配字符串是 “\\\\” ,首先经过字符串的转义,正则表达式使用的才是 \\

因此匹配一个反斜杠和一个正斜杠 \/ 的写法就有两种:

  • “\\\\/”
  • “\\\\\\/” 编辑器会提示Redundant Character Escape

Test Program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
String inputStr=":android\\/data";
Pattern PATTERN_BLOCK_PATH = Pattern.compile(".*:android\\/(?:data|obb|sandbox)$");
boolean match = PATTERN_BLOCK_PATH.matcher(inputStr).matches();
System.out.println(PATTERN_BLOCK_PATH.pattern()+ " match " + inputStr + " => " + match);

char c = 92;
PATTERN_BLOCK_PATH = Pattern.compile(".*:android" + c + c + "/(?:data|obb|sandbox)$");
match = PATTERN_BLOCK_PATH.matcher(inputStr).matches();
System.out.println(PATTERN_BLOCK_PATH.pattern()+ " match " + inputStr + " => " + match);

PATTERN_BLOCK_PATH = Pattern.compile(".*:android\\\\/(?:data|obb|sandbox)$");
match = PATTERN_BLOCK_PATH.matcher(inputStr).matches();
System.out.println(PATTERN_BLOCK_PATH.pattern()+ " match " + inputStr + " => " + match);

PATTERN_BLOCK_PATH = Pattern.compile(".*:android\\\\\\/(?:data|obb|sandbox)$");
match = PATTERN_BLOCK_PATH.matcher(inputStr).matches();
System.out.println(PATTERN_BLOCK_PATH.pattern()+ " match " + inputStr + " => " + match);

Output

1
2
3
4
5
.*:android\\/(?:data|obb|sandbox)$ match :android\\/data => false
.*:android\\\\/(?:data|obb|sandbox)$ match :android\\/data => true
.*:android\\\\/(?:data|obb|sandbox)$ match :android\\/data => true
.*:android\\\\\\/(?:data|obb|sandbox)$ match :android\\/data => true