import re
value_list = ['oper-status','downward','upward','some','mid']
regex = r"\$\d+"
test_str = "Test Succeeded!! value is within the range of $1-$2 ,$3 $4 its value is {{post['x']}}"
matches = re.finditer(regex, test_str)
i = 0
if len(value_list) > 1 :
for matchNum, match in enumerate(matches):
matchNum = matchNum + 1
i = i + 1
print ("{match}".format( match = match.group()))
test_str = re.sub(regex,value_list[i],test_str,count=i)
print test_str
我得到以下输出
$1
$2
$3
$4
Test Succeeded!! value is within the range of downward-upward ,upward some its value is {{post['x']}}
在我期待的时候
Test Succeeded!! value is within the range of downward-upward ,some mid its value is {{post['x']}}
我的代码有什么问题
因为您使用的是
count=i
,所以字符串将被替换为:i=1
->"Test Succeeded!! value is within the range of downward-$2 ,$3 $4 its value is {{post['x']}}"
i=2
->"Test Succeeded!! value is within the range of downward-upward ,upward $4 its value is {{post['x']}}"
i=3
->"Test Succeeded!! value is within the range of downward-upward ,upward some its value is {{post['x']}}"
您应该改用
count=1
这是因为在
re.sub
中指定count=i
而不是count=1
你可以用str.format来完成所有这些
通过在lambda表达式中将组1值转换为
int
来访问列表中的替换字符串时,直接将re.sub
与\$(\d+)
正则表达式一起使用:参见Python demo
这个一次性的regex替换将帮助您避免与原始方法类似的问题,也就是说,您用
count=i
替换的次数超过了必要的次数如果可以有
$12
(并且列表没有12个元素)这样的匹配项,请添加一个条件:见this Python demo
相关问题 更多 >
编程相关推荐