Python: Suppress lines not substituted

Hi all,

I started playing around with Python (2.6.6) trying to parse a file. No matter what I tried so far I am not able to print only the lines/group/backreference that have been affected by the substitution. Instead I get also the other lines too

File to parse:

        [serverClass:One] some more text
                config = alpha.cfg

        [serverClass:Two] some more text
                config = bravo.cfg

        [serverClass:Three] some more text
                config = charly.cfg

Current code:

import re

f = open('infile', 'r')

lines = f.readlines()

for line in lines:
        x = re.sub(r"^\s*\[serverClass:([^]]*)\] .*$", r"\1", line.rstrip())
        print(x)

I assume there is something needed like the behavior of sed 's -n and /p to basically print nothing but the lines that have been matched.

Output:

$ python ./mach.py
One
                config = alpha.cfg

Two
                config = bravo.cfg

Three
                config = charly.cfg

Expected output:

One
Two
Three

I saw that there are more functions/methods in the module re like re.group etc. but I would like to know why it doesn't work with my example.

Thanks in forward for a hint with this rather basic problem.

Cheers
zaxxon

we can skip the line using match ?

import re

f = open('infile', 'r')

lines = f.readlines()

for line in lines:
        if re.match('^.*:(.*)].*$',line.rstrip()):
                x = re.sub(r'^.*:(.*)].*$', r'\1', line.rstrip())
                print x
1 Like

Thank you, itkamaraj. I had it tried so far with match() and search() and it didn't work.
Now I just noticed why - I used:

re.match('<partial-pattern>', ...

...where I assumed I can use just a part of a pattern like when you use Linux/Unix grep ; this seems not working so I have to use at least something like:

re.match('.*<partial-pattern>.*', ...

cheers
zaxxon