我正在尝试在字符串中查找特定单词并将这些单词用<b>
. 以下是我所拥有的,但我想知道是否有更有效的常规方式来做到这一点?
void testSomething() {
def myText = "The quick brown fox is very feisty today"
def BOUNDS = /\b/
def myWords = "quick very"
def words = myWords.tokenize(" ").join("|")
def regex = /$BOUNDS($words)$BOUNDS/
def found = ''
myText.eachMatch(regex) { match ->
found += match[0] + ' '
}
assert found == 'quick very '
def foundList = found.tokenize(" ")
def newList = []
myText.tokenize(" ").each {word ->
if (foundList.contains(word))
word = "<b>${word}</b>"
newList.add(word)
}
assert "The <b>quick</b> brown fox is <b>very</b> feisty today" == newList.join(" ")
}