正则表达式和字符串操作

时间:2012-02-04 21:14:39

标签: regex string groovy replace

我有以下格式的字符串

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]和methodCall

注意:我想在groovy中做到这一点,这样做的有效方法是什么

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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);
?>