Groovy 字符串替换

Groovy string replace

我正在编写一些 Groovy 代码来获取本应成为推文的文本,并将所有主题标签转换为指向 Twitter 主题标签的网络链接。事实上,我的代码可以正常工作,但是当文本中有一个裸露的 # 时它会失败,这意味着要被读取为 "number sign" 而不是主题标签。

工作代码(边缘情况除外)是:

static replaceHashTags(input) {
    while (input.contains(/#/)) {
        input = input.replaceAll(/(.*)#(\w+)(.*)/, { all, before, hashtag, after ->
            "${before}<a href='https://twitter.com/hashtag/${hashtag}'>${hashtag}</a>${after}"
        })
    }

    input.replaceAll(/<a href='https:\/\/twitter.com\/hashtag/, '#<a href=\'https://twitter.com/hashtag')
}

我没有在找到解决方案之前破坏大部分工作的代码,而是编写了一个测试 class 来尝试我的新匹配代码。它失败了,我不明白为什么。这是测试 class:

class StringTest {
    def checkContains(string, expression) {
        string.contains(expression)
    }

    @Test
    void shouldTestSomethingElse() {
        assert (checkContains('This is a string', /is/)) // Passes
        assert !(checkContains('This is a string', /werigjweior/)) // Passes

        assert (checkContains('#This tweet starts with a hashtag', /#This/)) // Passes
        assert (checkContains('#This tweet starts with a hashtag', /#(\w+)/)) // Fails.
    }
}

如我所说,我不确定为什么最后一个 assert 失败了。我对这个练习的期望是我可以简单地将 while (input.contains(/#/)) { 替换为 while (input.contains(/#(\w+)/)) {...但事实并非如此。

我不相信 string.contains() 接受正则表达式作为参数。这对我有用:

def checkContains(string, expression) {
  string =~ expression
}

assert (checkContains('This is a string', /is/))
assert !(checkContains('This is a string', /werigjweior/))
assert (checkContains('#This tweet starts with a hashtag', /#This/))
assert (checkContains('#This tweet starts with a hashtag', /#(\w+)/))

使用==~匹配整个字符串。