[Solved] find substring using match regex


Since this is not quite HTML and any XML/HTML parser couldn’t help it you can try with regex. It seems that you want to find text in form

?drug <someData> ?disease

To describe such text regex you need to escape ? (it is one of regex special characters representing optional – zero or once – quantifier) so you need to place \ before it (which in String needs to be written as "\\").
Also part <someData> can be written as as <[^>]> which means,

  • <,
  • one or more non > after it,
  • and finally >

So regex to match ?drug <someData> ?disease can be written as

"\\?drug <[^>]+> \\?disease"

But since we are interested only in part <[^>]+> representing <someData> we need to let regex group founded contend. In short if we surround some part of regex with parenthesis, then string matched by this regex part will be placed in something we call group, so we will be able to get part from this group. In short final regex can look like

"\\?drug (<[^>]+>) \\?disease"
         ^^^^^^^^^---first group, 

and can be used like

String a = "?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/possibleDiseaseTarget> ?disease .";
String b = "?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/molecularWeightAverage> ?weight . ?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/possibleDiseaseTarget> ?disease";

Pattern p = Pattern.compile("\\?drug (<[^>]+>) \\?disease");
Matcher m = p.matcher(a);
while (m.find()) {
    System.out.println(m.group(1));
}
System.out.println("-----------");
m = p.matcher(b);
while (m.find()) {
    System.out.println(m.group(1));
}

which will produce as output

<http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/possibleDiseaseTarget>
-----------
<http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/possibleDiseaseTarget>

solved find substring using match regex