0

I'm in-place editing a file using fileinput as below.

for line in fileinput.input():

    line = re.sub(pattern1, repl1, line)
    line = re.sub(pattern2, repl2, line)
    print(line, end="")

I want to apply re.sub only once for each line. If first pattern matches and replaced, I don't need to inspect pattern2.

How do I codify it?

0

2 Answers 2

1

Use re.subn, it returns the text and the number of subs made

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="")

Or if you have many patterns:

for line in fileinput.input():

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

        if n:
            break

    print(line, end="")
Sign up to request clarification or add additional context in comments.

Comments

0

You can use re.search upfront to check if pattern1 exists and then make decision based on that:

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="")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.