0
for line in open(fname, 'r'): 
    if re.search('#', line):
        #print(line)
        pass
    elif re.search('# segment: retract', line):
        print(line)
        print('break here')
        break
    else:
        outfile.write(line)

The elif statement does not work, can anybody help me with a regexp that matches

"# segment: retract"

the code does not even enter the elif statement.

Thanks

2 Answers 2

3

I don't think this is regex is the prob. The condition needs to be reversed like

if re.search('# segment: retract', line):
    print(line)
    print('break here')
    break
elif re.search('#', line):
    #print(line)
    pass
else:
    outfile.write(line)

The problem is the first if condition catching all lines starting with # and else never happens.

Sign up to request clarification or add additional context in comments.

Comments

3

The first expression of the if clause will always match for lines containing '#'. So your more specific condition in the elif clause will never match since the more generic condition in the if clause is always executed. So you would test the more specific conditions first and move the more generic condition(s) into the elif part.

for line in open(fname, 'r'): 

    if re.search('# segment: retract', line):
        print(line)
        print('break here')
        break
    elif re.search('#', line):
        #print(line)
        pass
    else:
        outfile.write(line)

1 Comment

No need for regex at all. if '# segment: retract' in line: is enough.

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.