Compare 2 strings in Java upto a delimiter

一笑奈何 提交于 2019-12-11 03:24:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!