2

比如我要分类c*t => CLASS1,和d*g => CLASS2:

Pattern CXT = Pattern.compile("^c.*t$");
Pattern DXG = Pattern.compile("^d.*g$");

public int classify(String in) {
    if (CXT.matches(in)) return CLASS1;
    if (DXG.matches(in)) return CLASS2;
    return -1;
}

如果有很多模式模式,这是非常低效的。

假设所有模式都是正交的,很容易看到一个 DFA 中的单遍就足够了。那么,是否存在可以将所有模式组合在一起的正则表达式处理器?

4

3 回答 3

1

你应该看一下dk.brics.automaton包,它不是你要找的,但它是一个非常快速的状态机实现,带有BSD 许可证

因此,您可以构建自动机,它比正则表达式更快地为您进行分类。

于 2011-05-20T06:48:45.080 回答
0

你可以做例如(未测试):

Pattern pat = Pattern.compile("^((c.*t)|(d.*g))$");


public int classify(String in) {
    Matcher m = pat.matcher(in);
    if (m.matches()) {
        if ( m.group(2) != null ) {
             return C;
        }
        else if ( m.group(3) != null ) {
         return D;
        }
    }
    return -1;
}

但我不确定这会比您当前的代码更有效。无论哪种方式,您都必须比较所有可能模式的输入,无论是显式执行还是将其构建到正则表达式中

于 2011-05-20T06:36:13.947 回答
0
/^((c.*t)|(d.*g))$/

然后,您查看找到了哪个匹配项。如果您看到 $2,则返回 CLASS1。如果您看到 $3,则返回 CLASS2 等。

于 2011-05-20T06:37:54.433 回答