Find text between two words in Java

I want to get all the text between two words, wherever it is. For instance:

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

From the above line, I want to get the words between β€œone” and β€œtwo” in an array:

My result should be stored in an array as follows:

 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

  • Gniyar Zubair
+4
source share
4 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 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) .

+7
source

Check out the Java Pattern class, which allows you to use regular expressions to identify substrings and, therefore, split a large string. You need something like

 Pattern.compile("\bone\B"); 

to define "one." \b and \b are word matches. You need them in order not to accidentally coincide with "someone" and not with the word "one" (aside, I would recommend another separator, rather than the words "one", "two", etc.)

+1
source

The easiest way (written for the Groovy shell), minus any error handling:

 public String textBetweenWords(String sentence, String firstWord, String secondWord) { return sentence.substring(sentence.indexOf(firstWord) + firstWord.length(), sentence.indexOf(secondWord)); } String between = textBetweenWords("Hello my dear cousin!", "Hello", "cousin"); println("[" + between + "]") 
+1
source

Just use the indexOf and subString methods

0
source

All Articles