繁体   English   中英

在Java中使用正则表达式如何从字符串中的位置找到最后3个单词

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

在Java中使用正则表达式如何从字符串中的位置找到最后3个单词,例如我有一个字符串

它位于Bara Imambara附近,并在连接道路上站着一个雄伟的门户,称为Rumi Darwaza。 由于在特殊节日(例如穆哈拉姆邦)期间的装饰和枝形吊灯,该建筑也被称为光之宫

我想在我已经找到的“ Rumi Darwaza”之前找到最后3个字,并且在字符串中的位置为50。

首先,使用substring截去不需要的字符串部分。 然后应用一个正则表达式,捕获字符串末尾的最后三个单词:

"\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s*$"

这会将最后三个单词放入正则表达式的三个捕获组中。

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));
    }
}

上面产生了以下输出:

gateway
known
as

ideone上的演示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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