I would like to extract sub-string between certain two words using java.
For example:
This is an important example about regex for my work.
I would like to extract everything between "an" and "for".
What I did so far is:
String sentence = "This is an important example about regex for my work and for me";
Pattern pattern = Pattern.compile("(?<=an).*.(?=for)");
Matcher matcher = pattern.matcher(sentence);
boolean found = false;
while (matcher.find()) {
System.out.println("I found the text: " + matcher.group().toString());
found = true;
}
if (!found) {
System.out.println("I didn't found the text");
}
It works well.
But I want to do two additional things
If the sentence is:
This is an important example about regex for my work and for me.I want to extract till the first "for" i.e.important example about regexSome times I want to limit the number of words between the pattern to 3 words i.e.
important example about
Any ideas please?
someString.split(" "). it returns a array of Strings there each position is a word from your match.