String input = "one i am here fine two one hope your are also fine two one ok see you two;"; Pattern p = Pattern.compile("(?<=\\bone\\b).*?(?=\\btwo\\b)"); Matcher m = p.matcher(input); List<String> matches = new ArrayList<String>(); while (m.find()) { matches.add(m.group()); }
This will create a list of all text between βoneβ and βtwoβ.
If you need a simpler version that does not use lookaheads / lookbehinds, try:
String input = "one i am here fine two one hope your are also fine two one ok see you two;"; Pattern p = Pattern.compile("(\\bone\\b)(.*?)(\\btwo\\b)"); Matcher m = p.matcher(input); List<String> matches = new ArrayList<String>(); while (m.find()) { matches.add(m.group(2)); }
Note. Java arrays are based on level zero, not on one, so in your example, the first result will be in result[0] not result[1] . In my solution, the first match is in matches.get(0) .
source share