2012-12-08 37 views
4
protected void searchFilter(String s, int n) 
{ 
     RowFilter<MyTableModel, Object> rf = null; 
     try { 
      System.out.println(s); 
      rf = RowFilter.regexFilter(s, n); 
     } catch (PatternSyntaxException e) { 
      System.out.println(e); 
     } 
     filters.add(rf); 
    } 

我試圖匹配JTable中包含括號的字符串。在上面的代碼中,字符串參數可以是: 約翰(史密斯)與RowFilter匹配的括號(regexFilter)

和列我在快樂搜索:

Jane (Doe) 
John (Smith) 
John (Smith) 
Jack (Smith) 

,我想它返回:

John (Smith) 
John (Smith) 

但現在它不會返回任何東西。我查看了Matcher,Pattern和RowFilter的文檔,但迄今沒有任何幫助。

+0

這是真的嗎? 「我想讓它迴歸的地方:約翰(史密斯)約翰(史密斯)',不是約翰(史密斯)和傑克(史密斯) – mKorbel

+0

@mKorbel爲什麼不,列中包含兩次約翰(史密斯)。 –

回答

4

括號是正則表達式中的元字符。因此,你實際上試圖匹配John Smith(沒有括號)。你需要做的是逃避它們。

Java具有內置函數來自動轉義所有元字符:Pattern.quote。通過這個函數運行s,它應該修復它。

另請注意,您可能想用^...$圍繞該模式。否則,它會接受包含諸如This is John (Smith) foobar.之類的行(因爲如果正則表達式匹配輸入的子字符串,那麼它很高興)。