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 中包含括号的字符串。在上面的代码中,字符串参数可以是:John (Smith)

我正在搜索的列:

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

我希望它返回的地方:

John (Smith)
John (Smith)

但现在它没有返回任何东西。我查看了 Matcher、Pattern 和 RowFilter 的文档,但到目前为止没有任何帮助。

4

1 回答 1

4

括号是正则表达式中的元字符。因此,您实际上是在尝试匹配John Smith(不带括号)。你需要做的是逃离他们。

Java 有一个内置函数可以自动转义所有元字符:Pattern.quote. 运行s此功能,它应该修复它。

另请注意,您可能希望用 包围模式^...$。否则它将接受包含类似内容的行This is John (Smith) foobar.(因为正则表达式很高兴它可以匹配输入的子字符串)。

于 2012-12-08T12:57:28.790 回答