Regular expression and string operations

I have a line in the following format

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

I want to be replaced with

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

so two things replace [user: id] and the Call method

note: I want to do this in groovy, which would be an effective way to do this

+4
source share
2 answers

Groovy, child:

 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" 
+3
source

I don't know about groovy, but in PHP it will 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); ?> 
+1
source

All Articles