问题
String 1:
func1(test1)
String 2:
func1(test2)
I want to compare these 2 strings upto the first open braces '('.
So for the given example it should return true since the string upto '(' in both the strings is 'func1'.
Is there any way to do that without splitting?
回答1:
String#substring()
method will help on this case this combined with String#indexOf()
method
String x1 = "func1(test1)";
String x2 = "func1(test1)";
String methName1 = x1.substring(0, x1.indexOf("("));
String methName2 = x2.substring(0, x2.indexOf("("));
System.out.println(methName1);
System.out.println(methName2);
System.out.println(methName1.equals(methName2));
回答2:
You can use String.matches() method to test if the second string matches the splitted one from the first string:
String s1 = "func1(test1)";
String s2 = "func1(test2)";
String methName = s1.substring(0, s1.indexOf("("));
System.out.println(s2.matches(methName+ "(.*)"));
This is a working Demo.
回答3:
Alternatively you can compare the strings directly by replacing everything after '(' by empty string.
String str1 = "func1(test1)";
String str2 = "func1(test2)";
System.out.println(str1.replaceAll("\\(.*", "").equals(str2.replaceAll("\\(.*", "")));
回答4:
You can use regex to find every thing between any delimiters, in your case ()
and compare the results, for example :
String START_DEL = "\\("; //the start delimiter
String END_DEL = "\\)"; //the end delimiter
String str1 = "func1(test1)";
String str2 = "func1(test2)";
Pattern p = Pattern.compile(START_DEL + "(.*?)" + END_DEL);//This mean "\\((.*?)\\)"
Matcher m1 = p.matcher(str1);
Matcher m2 = p.matcher(str2);
if (m1.find() && m2.find()) {
System.out.println(m1.group(1).equals(m2.group(1)));
}
来源:https://stackoverflow.com/questions/43179650/compare-2-strings-in-java-upto-a-delimiter