Reputation: 225
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 ?
Upvotes: 1
Views: 3344
Reputation: 56
You could use String.split()
and the regex OR operator (if you know all possible delimiters already) and compare the arrays.
import java.utils.Arrays;
String pattern = "-|:";
if (Arrays.equals(s1.split(pattern), (s2.split(pattern)))) {
System.out.println("Match");
} else {
System.out.println("No match");
}
edited to use Arrays.equals
Upvotes: 2
Reputation: 61920
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.
Upvotes: 5