比较两个字符串以忽略java中的大小写和特殊字符?

时间:2016-01-04 12:10:41

标签: java arrays replaceall

    String s1 = "Madam,I'm Adam";
    String s2 = "madam i m adam";
    String str = s1.replaceAll("-,' "," ");
    System.out.println(str.equalsIgnoreCase(s2));    //  false 

我们如何使s1和s2相等?

2 个答案:

答案 0 :(得分:1)

使用像[^\\w\\d\\s]这样的正则表达式过滤字符串 - 不是字符,不是数字,不是空格:

public static void main(String[] args) {
    String s1 = "Madam,I'm Adam";
    String s2 = "madam i m adam";
    System.out.printf("  -> %s\n", normalizedEquals(s1, s2));    //  false     
}

static String normalize(String s) {
    // here goes normalization
    return s.replaceAll("[^\\w\\d\\s]", " ");
}

static boolean normalizedEquals(String s1, String s2) {
    s1 = normalize(s1);
    s2 = normalize(s2);
    System.out.printf("  -> %s\n  -> %s\n", s1, s2);
    return s1.equalsIgnoreCase(s2);
}

输出:

-> Madam I m Adam
-> madam i m adam
-> true

答案 1 :(得分:0)

添加以下行并且应该可以正常工作

String str = s1.replaceAll("[,']"," ");

测试正则表达式的最佳方法是http://regexr.com/