【问题标题】:How to implement a regex which tries to find the most similar match in Java?如何实现一个试图在 Java 中找到最相似匹配的正则表达式?
【发布时间】:2020-03-14 12:45:56
【问题描述】:

给定字符串“abc xyz def”,我希望字符串“abc def”和“def abc”都能成功匹配,如何使用Java 中的正则表达式完成此操作?

更多: 最佳解决方案可能类似于 python 中的正则表达式模块提供的模糊搜索,以便为正则表达式提供额外的功能。

【问题讨论】:

  • 你如何定义“def abc”与“abc xyz def”相似?
  • "abc xyz def" 包含单词 "def" 和 "abc"

标签: java regex fuzzy-search


【解决方案1】:

您想要的在正则表达式中称为“组”。组放置在括号 () 中,并且可以是规定字符类型的文字或符号化正则表达式语法。 java.util.Scanner 和其他相关的 Iterator 接口和类或 java.lang.String 和用于正则表达式的主包 java.util.regex 包含用于组捕获的工具。

String abc = null; // weird but true for building regex into the expression on the fly in a re-callable method
String abc = new String("abc");
// hazard a guess such a data ***mining*** techniques would appear like this to capture groups whether present of not
Pattern p =  "((\b)*"+abc+"(\b)*)*   |   ((\b)*xyz(\b)*)* |  ((\b)*def(\b)*)*";

【讨论】:

    【解决方案2】:

    希望对您有所帮助:

        String regex1 = "(.*)abc(.*)";
        String regex2 = "(.*)def(.*)";
        String s = "abc xyz def";
        if (Pattern.matches(regex1, s) & (Pattern.matches(regex2, s) ) ) {
            System.out.println("Correct");
        }
    

    【讨论】:

      猜你喜欢
      • 2015-11-11
      • 2018-05-05
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      相关资源
      最近更新 更多