无法让python替换正则表达式工作

时间:2012-11-15 08:21:44

标签: python regex replace

无法使代码生效,以下代码应该替换之后=和之后的内容。

user =" / silent test = de&#34 ;;

#!/usr/bin/python
import re
import fileinput

langids = ["de","uk","us","dk"]

for lang in langids:
 for line in fileinput.FileInput("C:\Users\HS\Desktop\sps_r2850\Test.txt",inplace=1):
    if re.match(".*user = \"[a-zA-Z/_= ]*\";.*", line):
        line = ("user = \"/silent test=_%s\";\n" % lang)
    print line,

1 个答案:

答案 0 :(得分:3)

使用re.sub更改语言:

import re

# no value set (or any doesn't matter)
line='user = "/silent test=";'

# values to insert 
langids = ["de","uk","us","dk"]

for lang in langids: 
     print re.sub('(.*=)(.*)(".*)',r'\1'+lang+r'\3',line)

# output
>>> user = "/silent test=de";
>>> user = "/silent test=uk";
>>> user = "/silent test=us";
>>> user = "/silent test=dk";