2010-06-03 46 views
1

我試圖從一個URL頁面名稱和查詢字符串,它不應該包含.html前瞻正則表達式產生意想不到的組

這是Java中的示例代碼:

public class TestRegex { 
    public static void main(String[] args) { 
     Pattern pattern = Pattern.compile("/test/(((?!\\.html).)+)\\?(.+)"); 
     Matcher matcher = pattern.matcher("/test/page?param=value"); 
     System.out.println(matcher.matches()); 
     System.out.println(matcher.group(1)); 
     System.out.println(matcher.group(2)); 
    } 
} 

通過運行此代碼可以得到以下的輸出:

真正

Ë

我的正則表達式有什麼問題,所以第二組包含字母e而不是param=value

回答

3

你這樣做:

Pattern.compile("/test/(((?!\\.html).)+)\\?(.+)") 
//      ^^   ^^ ^^ 
//      ||   | | | | 
//      |+------2-----+ | +-3+ 
//      |    | 
//      +-------1-------+     

嘗試:

換句話說:(?:...)使得非捕獲組。

+0

哇!驚人的全面! – yatskevich 2010-06-03 14:19:14

+0

@Ivan,很高興聽到! :) – 2010-06-03 16:25:18