簡體   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