Rob
Rob

Reputation: 53

Compare two strings to ignore case and special characters in java?

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

How can we make s1 and s2 equal ?

Upvotes: 0

Views: 10476

Answers (2)

coldy
coldy

Reputation: 2195

Added the below line and should work

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

Best way to test your regex are http://regexr.com/

Upvotes: 0

ankhzet
ankhzet

Reputation: 2568

Filter strings with regexp like [^\\w\\d\\s] - not charachters, not digits, not spaces:

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);
}

Output:

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

Upvotes: 1

Related Questions