正则表达式与字符串操作

4

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

blah blah [user:1] ho ho [user:2] he he he

我想要将它替换为:

blah blah <a href='1'>someFunctionCall(1)</a> ho ho <a href='2'>someFunctionCall(2)</a> he he he

即需要实现两个功能:替换[user:id]以及调用方法。

注意:我想在Groovy中完成,请问最有效的方法是什么?

2个回答

3

嗨,Groovy:

def someFunctionCall = { "someFunctionCall(${it})" }
assert "blah blah [user:1] ho ho [user:2] he he he"
    .replaceAll(/\[user:(\d+)]/){ all, id ->
    "<a href=\"${id}\">${someFunctionCall(id)}</a>"
    } == "blah blah <a href=\"1\">someFunctionCall(1)</a> ho ho <a href=\"2\">someFunctionCall(2)</a> he he he"

能够根据您之前的描述找到解决方案,谢谢。 - user602865

1

我不了解Groovy,但在PHP中它应该是:

<?php
$string = 'blah blah [user:1] ho ho [user:2] he he he';
$pattern = '/(.*)\[user:(\d+)](.*)\[user:(\d+)](.*)/';
$replacement = '${1}<a href=\'${2}\'>someFunctionCall(${2})</a>${3}<a href=\'${4}\'>someFunctionCall(${4})</a>${5}';
echo preg_replace($pattern, $replacement, $string);
?>

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