你的要求可以用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
?>
TestCase有时需要分批测试,请在@artt({....})内为文件内所有缺失应有tag的test case添加指定的测试tag.
例:
@artt({'P0': True, 'P1': True, 'reqId': ["12345"]})
添加 tag P2 -->
@artt({'P0': True, 'P1': True, 'P2': True, 'reqId': ["12345"]})
.sub(pattern, replace, string) 中的replace会替换掉整个match而不是哪一个capture group,
如果你想要保留match的其它部分只替换掉你想要的capture group,你非得将其他需要保留的部分也单独作为capture group用括号括起来,并在replace部分用 /1 /2 /3 ....的格式指代,在这种情况下,replace部分也要在引号前加 r 标用来跳过 / 符号。
如本例中,我先匹配所有 @artt({ 开头 reqId 结尾的内部不含 P2 的行,把 'reqId' 前面的所有部分保留,把 'reqId' 替换为 'P2': True, 'reqId'
注意,replace部分的写法要为 r"\1 'P2': True, 'reqId'"
参考
最后,如果希望在正则表达式内使用变量,可以用string类型的 .format() 方法将括号内的变量传入花括号 {} 的位置。
var str = "例如匹配到[url = baidu.com]百度[/url]"var reg = /\[url[\s\=]+([^\[\]]+)\]([^\[\]]+)\[\/url\]/g
str = str.replace(reg, "<a href='$1'>$2</a>")
console.log(str)