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

Viewed 437

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)
2 Answers

You can use

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

See this regex demo. Details:

  • \A - start of string
  • (?:!.*\n)+ - one or more lines starting with !
  • ! - a !,
  • \s* - zero or more whitespaces
  • (.*a\sb\sc\sd) - Group 1: any zero or more chars other than line break chars as many as possible, a, whitespace, b, whitespace, c, whitespace, d.

The replacement is the Group 1 value, \1.

Related