Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Text Between two words in Java

Tags:

text

search

I want to get all text in between 2 words wherver it is. For example:

String Testing="one i am here fine two one hope your are also fine two one ok see you two";

From the above string, I want to fetch the words between "one" and "two" in array:

My result should be stored in array like this:

String result[1] = i am here fine
String result[2] = hope your are also fine  
String result[3] = ok see you

How to do in java?

Thanks in advance

  • Gnaniyar Zubair
like image 667
Gnaniyar Zubair Avatar asked Jan 01 '10 10:01

Gnaniyar Zubair


1 Answers

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 the text between "one" and "two".

If you want a simpler version that doesn't 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 zero-based not one-based so in your example the first result would be in result[0] not result[1]. In my solution, the first match is in matches.get(0).

like image 199
cletus Avatar answered Sep 28 '22 14:09

cletus