-4

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?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97

2 Answers2

0

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);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 1
    My bad, I will provide a better mainString to illustrate. Consider String foo = "and If this is good and If that is good". I need to extract "that" by giving only the immediate predecessor and successor as the inputs in substringBetween() – Vidya Shankar NS Jun 27 '17 at 07:49
0

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());
}
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • I did try the above, 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()); } The output i get is "this" not "that". Any idea how to modify this so that it will return an array or a list of all elements that satisfy the regex? – Vidya Shankar NS Jun 27 '17 at 08:07
  • @VidyaShankarNS Instead if using `if(m.find()){`try using `while(m.find()){`, it will print all the matches. – Darshan Mehta Jun 27 '17 at 08:26
  • Thanks a lot for understanding my problem. This was what I wanted. Thanks again!! – Vidya Shankar NS Jun 27 '17 at 08:30