首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >匹配字符串中的单词并将其设置为粗体

匹配字符串中的单词并将其设置为粗体
EN

Stack Overflow用户
提问于 2013-01-10 03:05:43
回答 1查看 1.7K关注 0票数 2

我试图在字符串中找到特定的单词,并用<b>包装这些单词。下面是我所拥有的,但我想知道是否有更有效的时髦方法来做到这一点?

代码语言:javascript
运行
复制
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(" ")
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-10 03:17:44

当然,只要使用String.replaceAll()即可。

代码语言:javascript
运行
复制
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"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14244582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档