如果正则表达式匹配替换字符串并替换为其他正则表达式匹配的其他正则表达式

时间:2013-04-20 14:01:45

标签: python regex

我试图在满足某些条件后创建dict。以下是代码段:

def dic_gen(exc):
    param_errors = {re.sub(r"sss_", r"aaa_",err.name): err.address for err in exc.errors }
    param_errors["status"] = "ERROR"
    return param_errors

上面代码正在做的是它检查err.name是否有sss_然后删除它并创建一个dict。现在我还想添加另一个条件,如果它有“ttt_”然后用“bbb_”替换它是否可以使用re.sub?或者最有效的方法是什么?

感谢,

2 个答案:

答案 0 :(得分:0)

我不知道你打算怎么做但我会用:

abc = "Something_sss whatever"
result = abc.replace("_sss","_ttt")
print result

结果:

"Something_ttt whatever"

答案 1 :(得分:0)

通过传递re.sub()函数而不是替换字符串,您可以这样做:

def func(matchobj):
    return 'aaa_' if matchobj.group(0) == 'sss_' else 'bbb_'

def dic_gen(exc):
    param_errors = {re.sub(r'(sss_)|(ttt_)', func, err.name):
                       err.address for err in exc.errors}
    param_errors["status"] = "ERROR"
    return param_errors

由于函数只是一个表达式,你可以从中创建一个lambda并避免使用外部函数定义(尽管它使代码的可读性降低):

def dic_gen(exc):
    param_errors = {re.sub(r'(sss_)|(ttt_)', 
        lambda mo: 'aaa_' if mo.group(0) == 'sss_' else 'bbb_', err.name):
        err.address for err in exc.errors}
    param_errors["status"] = "ERROR"
    return param_errors