Groovy字符串替换

use*_*865 7 regex string groovy replace

我有以下格式的字符串

some other string @[Foo Foo](contact:2) some other string @[Bar Bar](contact:1) still some other string
Run Code Online (Sandbox Code Playgroud)

现在我想要这个字符串

some other string <a href="someurl/2">Foo Foo</a> some other string <a href="someurl/1">Bar Bar</a> still some other string
Run Code Online (Sandbox Code Playgroud)

所以基本上需要@[Some name](contact:id)使用groovy 替换to url并使用reg ex这是什么有效的方法

jam*_*man 11

您可以将Groovy replaceAllString方法与分组正则表达式一起使用:

"some other string @[Foo Foo](contact:2) some other string @[Bar Bar](contact:1) still some other string"
.replaceAll(/@\[([^]]*)]\(contact:(\d+)\)/){ all, text, contact ->
    "<a href=\"someurl/${contact}\">${text}</a>"
}
Run Code Online (Sandbox Code Playgroud)

/@\[([^]]*)]\(contact:(\d+)\)/=〜@[Foo Foo](contact:2)
/开始正则表达式
@匹配@
\[匹配[
(开始文本
[^]]*匹配Foo Foo
)结束文本
]匹配]
\(contact:匹配(contact:
(开始联系人
\d+匹配2
)结束联系人
\)匹配)
/结束正则表达式模式