2013-01-09 38 views
0

我試圖在字符串中找到特定單詞並用<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

當然,只是使用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" 
相關問題