How to delete a line with re?

P

Peng Yu

Hi,

I want to delete the line with abc in the following program. But the
following program does not do what I want. Can somebody let me know
how to do it?

Thanks,
Peng

#!/usr/bin/python

import re

file="""abcd
efg
hijk
lmn
"""

regex = re.compile("^abcd$", re.MULTILINE)

print file,
print "$"
print regex.sub('', file),
 
P

Peter Otten

Peng said:
I want to delete the line with abc in the following program. But the
following program does not do what I want. Can somebody let me know
how to do it?
file="""abcd
efg
hijk
lmn
"""

regex = re.compile("^abcd$", re.MULTILINE)
print regex.sub('', file),

What /do/ you want? If you want to remove the trailing newline

regex = re.compile("^abcd$\n?", re.MULTILINE)

might work.

Peter
 
J

John Machin

What /do/ you want? If you want to remove the trailing newline

regex = re.compile("^abcd$\n?", re.MULTILINE)

might work.

Not only might work, but does work, including covering the corner
cases where the abcd line is immediately followed by (1) an empty line
(2) no newline then end-of-file. It is also more elegant [yes, even
regular expressions can be elegant] than what I came up with (see
below).

Hint for the OP: repr() is your friend.
... efg
... abcd
...
... hijk
... abcd"""...
... hijk
... """
print repr(src) 'abcd\nefg\nabcd\n\nhijk\nabcd'
print repr(expected) 'efg\n\nhijk\n'
for pattern in ["^abcd$\n?", r"^abcd(\n|\Z)"]:
... regex = re.compile(pattern, re.MULTILINE)
... actual = regex.sub('', src)
... print repr(actual)
... print actual == expected
...
'efg\n\nhijk\n'
True
'efg\n\nhijk\n'
True
Cheers,
John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top