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

标签 java regex pattern-matching

在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

Demo on ideone.

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

相关文章:

string - perl中的子字符串比较

opencv - 确定球面上数据的旋转

c# - 正则表达式匹配需要很长时间才能执行

regex - 正则表达式将第一个单词与每行中的一个字符匹配

java - 使用 [3 :0] substring in it 解析字符串

java - 使用 java 在 sqlite SELECT 中的列之间添加逗号和空格

javascript - 带有阿拉伯语表达式的正则表达式

java - 错误启动创意。 JVM DLL C :\Program Files\Java\jdk1. 8.0_112 加载失败

java - Reactor 取消订阅的方式

java - 如何使用 Jersey REST 客户端在 REST url 中传递 java.util.date