正则表达式高级替换,匹配后进行运算,然后使用结果替换,怎么实现?
的有关信息介绍如下:你的要求可以用php语言或Python语言实现,因为它们的preg_replace_callback(Python用sub)函数参数中可以使用回调函数,
这样对处理你提的问题比较简便,其它语言也可以处理,但就比较麻烦.按照你的要求编写的Python程序如下
import re
def fun(matches):
return matches[1]+str(eval(matches[2]))
s="adfadfd,lat:12+2,lng:34+1,fdsfdsaf"
regex='(lat:|lng:)([0-9]+([+-][0-9]+)?)'
result=re.sub(regex,fun,s,re.I)
print(result)
源代码(注意源代码的缩进)
按照你的要求编写的PHP程序如下
<?php
function call_back($matches)
{
return $matches[1].eval("return $matches[2];");
}
$s="adfadfd,lat:12+2,lng:34+1,fdsfdsaf";
$regex='/(lat:|lng:)([0-9]+([+-][0-9]+)?)/i';
$result=preg_replace_callback($regex,"call_back",$s);
echo $result;
?>