2012-02-04 33 views
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

更换所以两件事更换[用户:ID]和一个方法调用

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

回答

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" 
+0

能够拿出来与你的感谢先前描述的解决方案 – user602865 2012-02-04 21:53:09

1

我不知道常规,但在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); 
?>