我有一個我想匹配的模式,但編譯器說這是不正確的。我應該如何糾正在java中的scape序列?轉義序列不正確
這是一種模式:
String patter = "\/\/s.ytimg.com\/yts\/jsbin\/html5player-en_US-vfllxLx6Z\/html5player.js"
我有一個我想匹配的模式,但編譯器說這是不正確的。我應該如何糾正在java中的scape序列?轉義序列不正確
這是一種模式:
String patter = "\/\/s.ytimg.com\/yts\/jsbin\/html5player-en_US-vfllxLx6Z\/html5player.js"
在任何情況下使用\
,它需要被複制,因爲\
被用來逃跑的特殊序列,例如\n
創建一個換行符。 \\
相當於實際url中的單個\
。
爲您的實際網址,使用:
String patter = "\\/\\/s.ytimg.com\\/yts\\/jsbin\\/html5player-en_US-vfllxLx6Z\\/html5player.js"
但是,如果你試圖逃跑的/
人物,那是不必要的。你可以用這個:
String patter = "//s.ytimg.com/yts/jsbin/html5player-en_US-vfllxLx6Z/html5player.js"
編譯器會抱怨,因爲沒有這樣的轉義字符如\/
。常見的轉義字符有這些:
\n
換行符\t
標籤要在字符串中嵌入文字\
,你需要使用\\
,例如:
String pattern = "\\/\\/s.ytimg.com\\/yts\\/jsbin\\/html5player-en_US-vfllxLx6Z\\/html5player.js";
但實際上,真的明白你爲什麼需要\
。我覺得你真的需要什麼是最有可能沒有\
可言:
String pattern = "//s.ytimg.com/yts/jsbin/html5player-en_US-vfllxLx6Z/html5player.js";
如果你想逃避\
那麼你需要使它像一倍\\
。你可以試試這個:
String patter = "\\/\\/s.ytimg.com\\/yts\\/jsbin\\/html5player-en_US-vfllxLx6Z\\/html5player.js";
你確定你需要''''之前'/'('/'在字符串或正則表達式中不是特殊的)嗎? – Pshemo 2014-09-06 18:33:32
是的,因爲我正在尋找的模式是以這種方式構建的。 – usercode2014 2014-09-06 18:39:35
在這種情況下,下面的每個答案都有正確的解決方案,因此當您的問題至少有15分鐘時間時,請隨時[接受](http://meta.stackexchange.com/a/5235/186652) (選擇你最喜歡的一個)。 – Pshemo 2014-09-06 18:44:02