[英]Match the last occurrence of a word in a string
當前,我正在用java swing實現一個文本框,該文本框突出顯示了關鍵字。 我參考了這個問題給出的第二個答案。 但是,我只希望突出顯示單詞的最后一次出現。
例如,當用戶鍵入"I have swimming at school at 7pm"
,我希望文本框僅突出顯示第二個"at"
。 我曾嘗試在正則表達式中使用負前瞻。 但這是行不通的。
我用(at(?!.at)|from|by)))
代替(at|from|by)
我嘗試了什么(從提供的鏈接中引用):
if (wordR == after || String.valueOf(text.charAt(wordR)).matches("\\W")) {
if (text.substring(wordL, wordR).matches("(\\W)*(at(?!.at)|from|by)"))
setCharacterAttributes(wordL, wordR - wordL, attr, false);
else
setCharacterAttributes(wordL, wordR - wordL, attrBlack, false);
wordL = wordR;
}
我認為正則表達式無法正常工作,因為用戶在鍵入時會進行檢查,但是不確定如何解決此問題。
為什么不使用這種方法 :
public int lastIndexOf(String str)
返回最后一次出現的指定子字符串在此字符串內的索引,從指定索引開始向后搜索。
如:
System.out.println("index = " + "I have swimming at school at 7pm".lastIndexOf("at"));
您可以使用lastIndexOf()
返回的值來設置Swing
組件中String
的屬性,但是顯然,您需要按以下說明重置以前所做的操作: 插入String后在Document中重置屬性
如果您不這樣做,則該單詞的每次出現都會突出顯示。
您必須使用正則表達式嗎? indexOf
具有一個起始位置作為從其開始搜索的第二個參數。 您只需要填寫第一個匹配項的位置即可。 示例腳本:
String haystack = "I have swimming at school at 7pm";
String needle = " at ";
int pos2 = haystack.indexOf(needle, haystack.indexOf(needle) + 1);
if (pos2 > -1) {
System.out.println("Found second '" + needle + "' at position " + pos2);
} else {
System.out.println("Could not find second '" + needle + '"');
}
輸出: Found second ' at ' at position 25
如果您也想打的話,程序會變得有些復雜at.
, at,
、、 at?
並at!
,但基本原理保持不變。
基本上,您可以在搜索詞前使用貪婪量詞:
Pattern p = Pattern.compile(".*\\b(at|from|by)\\b");
String s = "I have swimming at school at 7pm";
Matcher m = p.matcher(s);
if (m.lookingAt()) {
System.out.println(m.group(1));
}
因為.*
是貪婪的,所以您獲得了最后一個匹配項(或字符串末尾的第一個匹配項)。
這種方式的主要好處是,無論您搜索的單詞之前還是之后的字符都像標點符號一樣,它都能繼續工作,因為交替詞被單詞邊界包圍。 單詞邊界可以避免誤報,例如當另一個單詞中包含at
時。
注意:在替換上下文中,您需要捕獲字符串的開頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.