python正则表达式只应用一个替换

时间:2016-02-14 02:54:49

标签: python regex file

我使用SkeeNrID就地编辑文件,如下所示。

fileinput

我想对每一行只应用for line in fileinput.input(): line = re.sub(pattern1, repl1, line) line = re.sub(pattern2, repl2, line) print(line, end="") 一次。如果第一个模式匹配并替换,我不需要检查pattern2。

我如何编纂它?

2 个答案:

答案 0 :(得分:1)

使用re.subn,它返回文本和潜艇的数量

for line in fileinput.input():

    line, n = re.subn(pattern1, repl1, line)
    if not n:
        line, n = re.sub(pattern2, repl2, line)
    if not n:
        line, n = re.sub(pattern3, repl3, line)

    ...

    print(line, end="")

或者如果你有很多模式:

for line in fileinput.input():

    for pattern in patterns:
        line, n = re.subn(pattern, repl1, line)

        if n:
            break

    print(line, end="")

答案 1 :(得分:0)

您可以预先使用re.search来检查pattern1是否存在,然后根据该决定做出决定:

for line in fileinput.input():

    if re.search(pattern1, line):
        line = re.sub(pattern1, repl1, line)
    else:
        line = re.sub(pattern2, repl2, line)

    print(line, end="")