在java中使用正则表达式如何从字符串中的某个位置找到最后3个单词,例如我有一个字符串
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
我想找到“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
关于java - 在java中使用正则表达式如何从字符串中的某个位置找到最后3个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21192636/