Home > OS >  Regular expression to remove all lines that begin with a specific symbol and more
Regular expression to remove all lines that begin with a specific symbol and more

Time:11-10

I would like to use regular expressions to delete all lines that start with a '!', except the last one that starts with this character. Additionally all empty lines should be deleted.

! row 1

!that is row number 2

! - another row

! a b c d

0 1 2 3

4 5 6 7

8 9 10 11

desired output:

a b c d

0 1 2 3

4 5 6 7

8 9 10 11

So far, I got:

re.sub(r'(?m)^(?!.*a\sb\sc\sd)\#.*\n?', '', textstring)

CodePudding user response:

You can use

re.sub(r'\A(?:!.*\n) !\s*(.*a\sb\sc\sd)', r'\1', textstring)

See test it in regex101

  • Related