SoapFinder { public SortedSet<SubText> findSoaps(String text) { SortedSet<SubText> set = new TreeSet<>(); String tag = findSoapTag(text); if (tag == null) { return set; } String soapStartTag = "<" + tag + ":Envelope"; String soapEndTag = "</" + tag + ":Envelope>"; int end; int start; Pattern startPattern = Pattern.compile("((<\\?xml .*?\\?>[\\s\n]*)?" + soapStartTag + ")"); Matcher startMatcher = startPattern.matcher(text); while (startMatcher.find()) { start = startMatcher.start(1); end = text.indexOf(soapEndTag, start); if (start < 0 || end < 0) { break; } SubText subText = new SubText(start, end + soapEndTag.length()); set.add(subText); } return set; }  String findSoapTag(String string); SortedSet<SubText> findSoaps(String text);  }
@Test public void testFindSoap() throws Exception { String stringWithSoaps = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("soap/stringWithSoap.txt")); SoapFinder finder = new SoapFinder(); SortedSet<SubText> findSoaps = finder.findSoaps(stringWithSoaps); AssertJUnit.assertEquals(2, findSoaps.size()); SubText first = findSoaps.first(); AssertJUnit.assertEquals(38, first.getStart()); AssertJUnit.assertEquals(299, first.getEnd()); SubText last = findSoaps.last(); AssertJUnit.assertEquals(369, last.getStart()); AssertJUnit.assertEquals(645, last.getEnd()); }