简体   繁体   中英

in java using regex how can i find last 3 words from a position in string

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.

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

Demo on ideone.

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