2010-04-25 72 views

回答

14

使用negative lookbehind

"(?<!\\\\):" 

的原因四個反斜槓是:

  • 反斜線在正則表達式特殊字符,所以你需要在正則表達式\\匹配一個反斜槓。
  • 反斜槓必須在Java字符串中轉義,因此上述每個反斜槓必須寫爲\\,總共有四個反斜槓。

示例代碼:

Pattern pattern = Pattern.compile("(?<!\\\\):"); 
Matcher matcher = pattern.matcher("foo\\:x bar:y"); 
if (matcher.find()) { 
    System.out.println(matcher.start()); 
} 

輸出:

10 
1

您是否嘗試過使用字符類的補運算符?

String s1 = "foo : bar"; 
    String s2 = "foo \\: bar"; 

    Pattern p = Pattern.compile("[^\\\\]:"); 

    Matcher m = p.matcher(s1); 
    if(m.find()) { 
     System.out.println(m.group()); 
    } 

    m = p.matcher(s2); 
    if(m.find()) { 
     System.out.println(m.group()); 
    } 
+0

這無法匹配字符串開頭的':'。 – polygenelubricants 2010-04-26 06:36:49

相關問題