2012-12-08 35 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.之类的行(因为如果正则表达式匹配输入的子字符串,那么它很高兴)。