简体   繁体   中英

Find Text Between words in Java

I want to get all text in between 2 words(1st word is fixed[One] but 2nd is either of 2 words[Two]Or[Three] ).

Note :: There may be or may not be space between found text and 2nd word. For example:

One     i am  
here
Two
i am fine 
One     i am 
here 
 Two
i am fine 
One     i am  
here
Three
i am fine 
One     i am  
here 
 Two
i am fine

What i found is

Pattern p = Pattern.compile("(?<=\\bOne\\b)(.*?)(?=\\bTwo\\b)");

But this is not correct as It takes complete word.

"Two" is valid.
"fineTwo" is not valid.

It matches only on complete words, because you use word boundaries \\b . If you want to accept "fineTwo", then remove the first boundary

Pattern p = Pattern.compile("(?<=\\bOne\\b)(.*?)(?=Two\\b)");

To accept either "Two" or "Three" as end, use an alternation:

Pattern p = Pattern.compile("(?<=\\bOne\\b)(.*?)(?=(?:Two|Three)\\b)");

Try this:

for(String parseOne : Input.split("One"))
  for (String parseTwo : parseOne.split("Two"))
    for (String parseThree : parseTwo.split("Three"))
       System.out.println(parseThree.replace("One", "").replace("Two", "").replace("Three", "").trim());

getTextBetweenTwoWords method may work.

public static void main(String[] args)
{
    String firstWord = "One";
    String secondword = "Two";
    String text = "One Naber LanTwo";
    System.out.println(getTextBetweenTwoWords(firstWord, secondword, text));
}
private static String getTextBetweenTwoWords(String firstWord, String secondword, String text)
{
    return text.substring(text.indexOf(firstWord) + firstWord.length(), text.indexOf(secondword));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM