Groovy字符串替换

7

我有一个字符串,格式如下:

some other string @[Foo Foo](contact:2) some other string @[Bar Bar](contact:1) still some other string

现在我想将这个字符串转换为

some other string <a href="someurl/2">Foo Foo</a> some other string <a href="someurl/1">Bar Bar</a> still some other string

基本上需要用Groovy和正则表达式将@[某个名字](联系人:ID)替换为URL,那么最高效的方法是什么?

2个回答

11
你可以使用Groovy的 replaceAll 字符串方法,结合一个分组正则表达式:
"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>"
}

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


你能否帮我解决这个问题:https://dev59.com/IGDVa4cB1Zd3GeqPZg9E? - user602865

1

您没有提到编程语言,但是一般假设该语言以某种 s/// 类型的正则表达式语法为基础:

s/@\[([^\]]+)\]\([^:]+:([0-9]+)\)/<a href="someurl\/$2">$1<\/a>/g

这在大多数正则表达式语言中都可以工作。例如,在Perl中它可以工作(尽管我正在转义Perl中具有特殊含义的@字符):

#echo "some other string @[Foo Foo](contact:2) some other string @[Bar Bar](contact:1) still some other string" | perl -p -e 's/\@\[([^\]]+)\]\([^:]+:([0-9]+)\)/<a href="someurl\/$2">$1<\/a>/g' 
some other string <a href="someurl/2">Foo Foo</a> some other string <a href="someurl/1">Bar Bar</a> still some other string

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接