Reputation: 383
in java using regex how can i find last 3 words from a position in string for example i have an string
It is situated near the Bara Imambara and on the connecting road stands an imposing gateway known as Rumi Darwaza. The building is also known as the Palace of Lights because of its decorations and chandeliers during special festivals, like Muharram
i want to find last 3 words before "Rumi Darwaza" which i already found and have position 50 in the string.
Upvotes: 1
Views: 288
Reputation: 726589
First, use substring
to chop off the part of the string that you do not need. Then apply a regular expression that captures the last three words before the end of the string:
"\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s*$"
This would put the last three words into three capturing groups of the regex.
String str = "It is situated near the Bara Imambara and on the connecting road stands an imposing gateway known as Rumi Darwaza. The building is also known as the Palace of Lights because of its decorations and chandeliers during special festivals, like Muharram";
int index = str.indexOf("Rumi Darwaza");
Matcher m = Pattern.compile("\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s*$").matcher(str.substring(0, index));
if (m.find() && m.groupCount() == 3) {
for (int i = 1 ; i <= 3 ; i++) {
System.out.println(m.group(i));
}
}
The above produces the following output:
gateway
known
as
Upvotes: 1