Regular expression and string operations

2019-05-07 20:46发布

问题:

I have String in the following format

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

I want it to be replaced by

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

so two things replacement of [user:id] and a methodCall

note: I want to do it in groovy, what would be the efficient way of doing it

回答1:

Groovy, baby:

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"


回答2:

I don't know about groovy, but in PHP it would be :

<?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);
?>