2017-06-07 23 views
2

我只是想用正則表達式反斜槓(\)字符匹配,但它拋出一個PatternSyntaxException有什麼問題:Pattern pattern = Pattern.compile(「\」);

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 
\ 
^ 
    at java.util.regex.Pattern.error(Unknown Source) 
    at java.util.regex.Pattern.compile(Unknown Source) 
    at java.util.regex.Pattern.<init>(Unknown Source) 
    at java.util.regex.Pattern.compile(Unknown Source) 
    at helloworld.HelloWorld.main(HelloWorld.java:20) 
+1

使用'「\\\\」'因爲你需要躲避Java字符和正則表達式字符。 – Berger

+0

重複的https://stackoverflow.com/questions/4025482/cant-escape-the-backslash-with-regex –

+0

你正在逃避轉義字符,它再次將該符號視爲未轉義。嘗試「\\\\」。 – vegaasen

回答

2

你只是想僅使用正則表達式轉義字符\(這就是爲什麼是一個正則表達式提出java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \

只要是明確的,順便說一句,在Java中的斜線\也用於標識逃脫序列(java escape characters)開始的字符和有特殊含義的編譯器。所以如果你想在一個字符串中寫一個斜槓,你必須加倍("\\")。

如果你想編寫一個搜索斜槓的正則表達式,你必須轉義它,並且在Java字符串中翻譯正則表達式,你必須再次翻兩倍斜槓。

所以對於斜線正則表達式變得"\\\\"