联合正则表达式匹配Java中的标记

时间:2014-09-03 00:05:43

标签: java regex string

我有一个很大的List<String>,其中每个字符串都是一个包含1 +&#34;令牌的句子&#34; (前缀为&#34; a&#34;或&#34; b&#34;后跟一个正整数):

List<String> tokenList = new ArrayList<String>()
tokenList.add("How now a1 cow.")
tokenList.add("The b1 has oddly-shaped a2.")
tokenList.add("I like a2! b2, b2, b2!")
// etc.

我想编写一个接受vararg标记列表的函数,并返回包含 all 标记参数的String tokenList的子集。例如:

public class TokenMatcher {
    List<String> tokenList; // Same tokenList as above

    List<String> findSentencesWith(String... tokens) {
        List<String> results = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();

        // Build up the regex... (TODO: this is where I'm going wrong)
        for(String t : tokens) {
            sb.append(t);
            sb.append("|");
        }

        String regex = sb.toString();

        for(String sentence : tokenList) {
            if(sentence.matches(regex)) {
                results.add(sentence);
            }
        }

        return results;
    }
}

同样,必须以这样的方式构造正则表达式:全部传递给函数的tokens必须存在于句子中才能使匹配成立。因此:

TokenMatcher matcher = new TokenMatcher(tokenList);
List<String> results = matcher.findSentencesWith("a1");     // Returns 1 String ("How now a1 cow")
List<String> results2 = matcher.findSentencesWith("b1");    // Returns 1 String ("The b1 has oddly-shaped a2.")
List<String> results3 = matcher.findSentencesWith("a2");    // Returns the 2 Strings with a2 in them since "a2" is all we care about...
List<String> results4 = matcher.findSentencesWith("a2", "b2");  // Returns 1 String ("I like a2! b2, b2, b2!.") because we care about BOTH tokens

最后一个例子(results4)很重要,因为虽然&#34; a2&#34;令牌出现在几个句子中,results4我们要求该方法为包含两个令牌的句子提供匹配。这是n-ary conjunctive,这意味着如果我们指定50个令牌作为参数,我们只需要包含所有50个令牌的句子。

以上findSentencesWith示例是我迄今为止的最佳尝试。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

鉴于您声明的要求,订单和频率都不重要,我认为在这种情况下根本不需要使用 regexes

相反,您可以将每个字符串与提供的所有示例标记进行比较,并查看字符串中是否包含所有标记。如果是这样,它就在结果集中。第一次检测到丢失的令牌时,该字符串将从结果集中删除。

这种代码看起来像这样:

<强> TokenMatcher.java

package so_token;

import java.util.*;    

public class TokenMatcher {

    public TokenMatcher(List<String> tokenList) {
        this.tokenList = tokenList;
    }

    List<String> tokenList;

    List<String> findSentencesWith(String... tokens) {
        List<String> results = new ArrayList<String>();

        // start by assuming they're all good...
        results.addAll(tokenList);

        for (String str : tokenList) {
            for(String t : tokens) {
                // ... and remove it from the result set if we fail to find a token
                if (!str.contains(t)) {
                    results.remove(str);

                    // no point in continuing for this token
                    break;
                }
            }
        }

        return results;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        List<String> tokenList = new ArrayList<String>();
        tokenList.add("How now a1 cow.");
        tokenList.add("The b1 has oddly-shaped a2.");
        tokenList.add("I like a2! b2, b2, b2!");

        TokenMatcher matcher = new TokenMatcher(tokenList);

        List<String> results = matcher.findSentencesWith("a1");     // Returns 1 String ("How now a1 cow")

        for (String r : results) {
            System.out.println("1 - result: " + r);
        }

        List<String> results2 = matcher.findSentencesWith("b1");    // Returns 1 String ("The b1 has oddly-shaped a2.")

        for (String r : results2) {
            System.out.println("2 - result: " + r);
        }

        List<String> results3 = matcher.findSentencesWith("a2");    // Returns the 2 Strings with a2 in them since "a2" is all we care about...

        for (String r : results3) {
            System.out.println("3 - result: " + r);
        }       

        List<String> results4 = matcher.findSentencesWith("a2", "b2");  // Returns 1 String ("I like a2! b2, b2, b2!.") because we care about BOTH tokens

        for (String r : results4) {
            System.out.println("4 - result: " + r);
        }
    }
}

这导致以下输出:

1 - result: How now a1 cow.
2 - result: The b1 has oddly-shaped a2.
3 - result: The b1 has oddly-shaped a2.
3 - result: I like a2! b2, b2, b2!
4 - result: I like a2! b2, b2, b2!

ideone上稍微调整一下,可运行的代码(主要是没有包名和非公共类,因此它将在网站上运行)。

注意:根据您提供的信息,由于该功能正在接受令牌列表,因此contains似乎足以确定令牌是否存在。但是,如果事实证明存在额外的限制,例如令牌后面必须跟一个空格或一组标点符号,或类似的东西,以便算作一个标记,那么我 建议使用 regexes - 基于个人令牌 - 将contains替换为matches并传入 regex 定义你想要什么围绕令牌。

可能还需要一个功能来验证传递给tokenList函数的findSentencesWith