Currently, I am implementing a textbox in java swing, which highlights the keywords. I referenced to the 2nd answer given in this question. However, I want only the last occurrence of the word to be highlighted.
For example, when the user is typing "I have swimming at school at 7pm"
, I want the textbox to highlight only the second "at"
. I have tried using the negative lookahead in the regex. But it is not working.
I used (at(?!.at)|from|by)))
instead of (at|from|by)
What I have tried (Referenced from the link provided):
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;
}
I think the regex is not working as the checking is happening while the user is typing, but am not sure on how to solve this problem.