Extracting a substring based on second occurence using Java - substringBetween() function

966 views Asked by At

I have the following string "If this is good and if that is bad". The requirement is to extract the string "that" from the main string.

Using

substringBetween(mainString, "If", "is") returns the string "this".

Could you please help in extracting the required string in this case. If this is not possible using the function substringBetween(), is there any alternative string function to achieve this?

2

There are 2 answers

3
Darshan Mehta On BEST ANSWER

You can use regex and Pattern matching to extract it, e.g.:

String s = "If this is good and if that is bad";
Pattern pattern = Pattern.compile("if(.*?)is");
Matcher m = pattern.matcher(s);
if(m.find()){
    System.out.println(m.group(1).trim());
}
1
ΦXocę 웃 Пepeúpa ツ On

you mean StringUtils.substringBetween(foo, "if", "is") instead of StringUtils.substringBetween(foo, "If", "is") because the method substringBetween is case sensitive operation enter image description here

and searching between "If" and "is" is not the same result as between "if" and "is"

String foo = "If this is good and if that is bad";
String bar = StringUtils.substringBetween(foo, "if", "is");
// String bar = StringUtils.substringBetween(foo, "If", "is");
System.out.println(bar);