Regex to match group of lines unless they contain a string

Viewed 40

I can't seem to write a regex to match a group of lines delimited by two specific strings, unless a third string is present within this group.

Example. Given this chunk of code:

func foo() {
   print("foo")
   dontmatchme
}

func foo2() {
   print("foo2")
}

func foo3() {
   print("foo")
   dontmatchme
}

I want to only match foo2, because it doesn't contain the string dontmatchme inside the body of the function.

I'm using func foo.*(\n|.)*?(}) to match the functions, but I can't seem to use a lookbehind correctly, to avoid matching the ones containing dontmatchme.

Thanks!

1 Answers

You may use a negative lookahead like this:

func foo(?![^}]*dontmatchme)[^}]*}

RegEx Demo

RegEx Details:

  • func foo: Match func foo text
  • (?![^}]*dontmatchme): Negative lookahead to fail the match if we have dontmatchme ahead of the current position before matching }
  • [^}]*: Match 0 or more of any chars except }
  • }: Match a }
Related