2010-06-15 56 views

回答

0

擴展「包含」關係的模式匹配總是對用戶來說很難。用戶可能會理解的是,對於任意數據的簡單使用「*」和「?」只有一個任意字符。

這就像SQL「喜歡」一樣,我真的很想向用戶展示「喜歡」,他們也喜歡。

0

一個Apache的百科全書類簡單的水珠,只有使用*和?作爲特殊字符,應該很容易將它們轉換爲正則表達式模式,而無需拉入全新的庫。下面的代碼是未經測試,但我使用了非常類似於SQL翻譯「喜歡」表達式正則表達式的東西:

public static boolean globMatches(String glob, String target) { 
    Pattern p = Pattern.compile("(\\*+)|(\\?)|([^*?]+)"); 
    Matcher m = p.matcher(glob); 
    StringBuilder sb = new StringBuilder(); 
    while (m.find()) { 
     String star = m.group(1); 
     String question = m.group(2); 
     String text = m.group(3); 
     if (star != null) { 
      sb.append(".*"); 
     } 
     else if (question != null) { 
      sb.append("."); 
     } 
     else { 
      sb.append(Pattern.quote(text)); 
     } 
    } 

    return target.matches(sb.toString()); 
} 
+0

一個漂亮的解決方案,但會發生什麼在用戶試圖搜索文字\ *?我們也需要爲此添加支持。再加上角落案例......我認爲對於像這樣的任務來說,圖書館是一個更好的解決方案。 – 2010-06-16 07:19:12