【问题标题】:Conjunctive regex matching tokens in JavaJava中的连接正则表达式匹配标记
【发布时间】:2014-09-03 00:05:43
【问题描述】:

我有一个很大的List<String>,其中每个字符串都是一个包含 1+ 个“标记”的句子(以“a”或“b”为前缀,后跟一个正整数):

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 标记列表,并将返回包含 所有 标记参数的字符串的 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;
    }
}

同样,正则表达式的构造方式必须是 all 传递给函数的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) 很重要,因为尽管“a2”标记出现在多个句子中,但 results4 我们要求该方法为包含 both 标记的句子提供匹配.这是 n-ary conjunctive,这意味着如果我们指定 50 个标记作为参数,我们只需要包含全部 50 个标记的句子。

上面的findSentencesWith 例子是我迄今为止最好的尝试。有什么想法吗?

【问题讨论】:

  • lookaheads 组合起来以独立于匹配顺序对您有帮助吗?要匹配包含任意位置 a2b2c2 的任何字符串,它将是:^(?=.*a2)(?=.*b2)(?=.*c2)。好吧,可能不是,你需要什么;)
  • 谢谢@Jonny5 (+1) - 听起来不错,但我仍然不明白这一切是如何结合在一起的(也许你可以用完整的代码示例发布答案?)。我不关心顺序或频率(也就是说,如果我可以findSentencesWith("a2") 我不在乎一个句子是否包含 1 个 a2 实例或 100,000 个实例)。再次感谢!

标签: java regex string


【解决方案1】:

鉴于您提出的顺序和频率都不重要的要求,我认为在这种情况下根本不需要使用 regex

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

这种代码看起来像这样:

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 似乎足以确定令牌是否存在。但是,如果事实证明对此有额外的限制,例如标记必须后跟一个空格或一组标点符号中的一个,或者类似的东西,才能算作一个标记,那么我 建议使用 regexs -- 在单个令牌的基础上 -- 将 contains 替换为 matches 并传入 regex 来定义您想要围绕的内容令牌。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    相关资源
    最近更新 更多