Maverick :
I want to compare two strings, which has a different delimiter in between.
Example
String s1 = "ZZ E5 - Pirates of carribean";
String s2 = "ZZ E5 : Pirates of carribean";
I want to compare if two strings are equal.
I've tried using regex in Java to solve this,
String pattern = "(.*)[:-](.*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(s1);
Matcher m1 = r.matcher(s2);
if (m1.find()&&m.find()) {
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
System.out.println("Found value: " + m1.group(1));
System.out.println("Found value: " + m1.group(2));
System.out.println(m.group(1).contentEquals(m1.group(1)));
System.out.println(m.group(2).contentEquals(m1.group(2)));
} else {
System.out.println("NO MATCH");
}
Is this a good approach or we can do this in some other efficient way ?
Dani Mesejo :
You could convert both strings to a canonical form by choosing one of the delimiters as canonical, for example:
String s1 = "ZZ E5 - Pirates of carribean";
String s2 = "ZZ E5 : Pirates of carribean";
String canonicalS1 = s1.replaceAll("-", ":");
String canonicalS2 = s2.replaceAll("-", ":");
System.out.println(canonicalS1.equals(canonicalS2));
Output
true
Note that this solution expects that the delimiters appear only one time, or for that matter that the delimiters are interchangeable.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=310284&siteId=1