re.sub显示异常行为

时间:2016-11-30 10:30:11

标签: python regex

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']}}

我的代码有什么问题

3 个答案:

答案 0 :(得分:0)

因为您使用的是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代替。

答案 1 :(得分:0)

通过{1}}正则表达式直接使用re.sub,同时通过将lambda表达式中的Group 1值转换为\$(\d+),从列表中访问替换字符串:

int

请参阅Python demo

这一次通过正则表达式替换将帮助您避免使用原始方法时遇到的问题,即您使用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']}}" print re.sub(regex,lambda x: value_list[int(x.group(1))], test_str) 替换的次数超过了必要时间。

如果可以有count=i之类的匹配(且列表没有12个元素),请添加条件:

$12

请参阅this Python demo

答案 2 :(得分:0)

这是因为您在count=i

中指定了count=1而不是re.sub
  • 在第一次迭代时,i = 1,$ 1被替换
  • 在第二次迭代时,i = 2,$ 2 $ 3被替换
  • 在第3次迭代时,i = 3,$ 4被替换
  • 在第4次迭代时,i = 4,没有任何东西可以替换

您可以使用str.format

完成所有这些操作
value_list = ['oper-status','downward','upward','some','mid']
test_str = "Test Succeeded!! value is within the range of {x[1]}-{x[2]} ,{x[3]} {x[4]} its value is {{post['x']}}".format(x=value_list)
# "Test Succeeded!! value is within the range of downward-upward ,some mid its value is {post['x']}"