2

我正在尝试在字符串中查找特定单词并将这些单词用<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(" ")
}
4

1 回答 1

0

当然,只需使用String.replaceAll().

def myText = "The quick brown fox is very feisty today"
def myWords = ['quick', 'very']

myWords.each {
    myText = myText.replaceAll(it, "<b>$it</b>")
}

assert myText == "The <b>quick</b> brown fox is <b>very</b> feisty today"
于 2013-01-09T19:17:43.540 回答