自定义占位符的时髦正则表达式



我有这个时髦的代码:

s = "${FirstAttribute} - DPA - ${Second Name}"
log.warn(s)
regex = "\" + "$\{\w+\s*\w*\}"
log.warn(regex)
matcher = ( s=~ regex )
log.warn("" + matcher.matches())
if (matcher.matches()) {
log.warn(matcher.getCount()+ " occurrence of the regular expression was found in the string.");
log.warn(matcher[0] + " found!")
}

这个想法是匹配 ${} 容器并提取其内容。根据此工具,正则表达式应该可以工作。但是,它仅在传递具有一次出现的字符串时才有效,例如"${FirstAttribute} - DPA"如果存在另一个出现,则未检测到任何内容(即matcher.matches() == false(

我一定错过了一些很少的东西,有人能指出我正确的方向吗?

您可以使用findAll来获取所有匹配项,但这不允许作为匹配器一部分的组仅提取中间位:

s = '${FirstAttribute} - DPA - ${Second Name}'
regex = /${[^}]+}/
assert s.findAll(regex) == ['${FirstAttribute}', '${Second Name}']

最新更新