【问题标题】:match incoming string with lookup strings将传入字符串与查找字符串匹配
【发布时间】:2017-04-08 11:53:24
【问题描述】:

我正在努力实现一项要求。

我正在接收文件,每个文件的前 50 个字符内都包含一些秘密信息。

例如它是我的输入文件字符串

String input = "Check      this     answer and you can find the keyword with this code";

然后我有一个下面给出的查找文件

查找字符串

this answer|Do this
not answer|Do that
example yes|Dont do

我想将前 50 个字符中可能出现的秘密信息与查找字符串进行匹配。 就像在我的示例中,查找字符串中的“this answer”与“this answer”匹配,但存在空格。

所以价值是存在的,但有额外的空间。这不是问题。有重要的信息。所以这是一场比赛

在信息匹配后,我将使用查找字符串中的操作信息。就像在这个例子中是“这样做”

如何使用 java 或 regex 进行这种匹配?

我已经尝试了包含 java 的函数,但没有得到我正在寻找。

提前感谢所有建议

【问题讨论】:

  • 您的问题提到了 Java,但您已使用 JavaScript 对其进行了标记。我根据string 猜测这应该是一个 Java 问题,所以我重新标记了它。

标签: java regex


【解决方案1】:

从字符串中删除空格或在查找字符串中的单词之间添加"\s*"

【讨论】:

    【解决方案2】:

    我会这样做:

    String input = "Check      this     answer and you can find the keyword with this code";
    Map<String, String> lookup = new HashMap<String, String>();
    lookup.put(".*this\\s+answer.+", "Do this");
    lookup.put(".*not\\s+answer.+", "Do that");
    lookup.put(".*example\\s+yes.+", "Dont do");
    
    for (String regexKey : lookup.keySet()) {
        if (input.matches(regexKey)) {
            System.out.println(lookup.get(regexKey));
        }
    }
    

    或者确保匹配在前 50 个字符中:

    String input = "Check      this     answer and you can find the keyword with this code";
    Map<String, String> lookup = new HashMap<String, String>();
    // Match with ^ from beginning of string and by placing parentheses we can measure the matched string when match is found.
    lookup.put("(^.*this\\s+answer).*", "Do this");
    lookup.put("(^.*not\\s+answer).*", "Do that");
    lookup.put("(^.*example\\s+yes).*", "Dont do");
    
    
    for (String regexKey : lookup.keySet()) {
        Matcher matchRegexKey = Pattern.compile(regexKey).matcher(input);
        if (matchRegexKey.matches()) {
            // Check match is in first 50 chars.
            if (matchRegexKey.group(1).length() <= 50) {
                System.out.println(lookup.get(regexKey));
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      相关资源
      最近更新 更多