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)