在java中,使用regex如何从字符串中的一个位置找到最后3个单词,例如,我有一个字符串。
它位于巴拉伊姆巴拉附近,在连接的道路上矗立着一个名为鲁米·达瓦扎的宏伟门户。这座建筑也被称为灯光宫,因为它的装饰和吊灯在特殊的节日,如穆哈拉姆
我想在"Rumi Darwaza“之前找到最后三个词,我已经找到了,并且在字符串中有第50位。
发布于 2014-01-17 18:01:00
首先,使用substring砍掉不需要的字符串部分。然后应用一个正则表达式,该表达式捕获字符串结尾前的最后三个单词:
"\\s(\\S+)\\s(\\S+)\\s(\\S+)\\s*$"这将把最后三个单词放入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));
}
}以上输出的结果如下:
gateway
known
as关于理想的演示。
https://stackoverflow.com/questions/21192636
复制相似问题