繁体   English   中英

如何比较两个字符串而忽略目标字符串的某些子字符串

[英]How to compare two string with ignoring some substring of the target string

假设我有两个字符串

String 1: You have transferred balance 1000. Transaction ID:12345670
String 2: You have transferred balance 1000. Transaction ID:@ignore

我想将第二个字符串与第一个字符串进行比较,并忽略带有某种关键字的动态交易ID部分(例如:-@ignore)。 因此,在比较第二个字符串和第一个字符串时,如果它在目标字符串的位置找到了关键字,它将忽略源字符串中的特定部分并返回true。

可以用Java完成此操作吗?是否有任何Java库可用于此类操作?

试试下面的这个

        final String s1 ="You have transferred balance 1000, Transaction ID:12345670";
        final String s2 = "You have transferred balance 1000, Transaction ID:@ignore";

        final String[] s1Split = s1.split(":");
        final String[] s2Split = s1.split(":");

        System.out.println(s1Split[0].equals(s2Split[0]));

使用正则表达式而不是第二个字符串。 这可以通过String.matches完成:

String string = "You have transferred balance 1000. Transaction ID:12345670";
if (string.matches(
  "You have transferred balance 1000. Transaction ID:\\d+")) { ...

将您的关键字@ignore替换为regEx,然后进行比较。

因此,您可以在字符串2中的任何位置放置@ignore,以在比较时忽略字符串1的任何部分。

例如:

字符串str2 =您已转移@ignore1000。事务ID: @ignore “”

  String str1 = new String("You have transferred balance 1000. Transaction ID:12345670");
  String str2 = new String("You have transferred balance 1000. Transaction ID:@ignore");

  String regEx =  str2.replace("@ignore", "(.*)");

  System.out.print("Result :" );
  System.out.println(str1.matches(regEx));

只需将模板转换为正则表达式模式即可。

String s1 ="You have transferred balance 1000, Transaction ID:12345670";
String s2 = "You have transferred balance 1000, Transaction ID:@ignore";

System.out.println(matches(s1, s2));

boolean matches(String text, String template) {
    StringBuilder sb = new StringBuilder("(?s)"); // Dot also for line breaks.
    for (int i = 0; i < template.length(); ++i) {
        int j = template.indexOf("@ignore", i);
        if (j == -1) {
            // Escape (quote) the regex special chars in as-is text.
            sb.append(Pattern.quote(template.substring(i));
            break;
        }
        sb.append(Pattern.quote(template.substring(i, j));
        j += "@ignore".length();
        sb.append(".*?"); // Shortest sequence.
    }
    return text.matches(sb.toString());
}

注意:该模式与整个文本匹配,因此,“查找”应以"(?s).*" + actualPattern + ".*"

如果@ignore语句不在末尾,则可以拆分包含它的String并检查第一个String是否以各个部分开头和结尾。

    String b = "You have transferred balance 1000. Transaction ID:12345670 Some more information:1234567";
    String a = "You have transferred balance 1000. Transaction ID:@ignore Some more information:1234567";

    String[] parts = a.split("@ignore");

    System.out.println(b.startsWith(parts[0]) && b.endsWith(parts[parts.length-1]));

这不涉及存在多个@ignore标记的情况,但是您将不得不替换第一个字符串中@ignore的相应部分,因此需要有关它的更多信息,例如长度或用于开始和结束的标记。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM