我正在尝试在字符串中查找特定单词并用<b>
包装这些单词。以下是我所拥有的,但我想知道是否有更有效的groovyish方式来做到这一点?
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(" ")
}
答案 0 :(得分: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"