Regex: Match double new lines but not within backticks

Viewed 39

I am trying to match all double new lines, but not within backticks. I am not familiar with lookbehinds, but I think that is what's needed here. This is what I've come up with this far: (?<!`)[\r\n]{2}. Somehow I need to add .*? or similar after the lookbehind and before the line break but I haven't figured it out yet.

Here you can see what should match, and what shouldn't.

        Some random text...
  // MATCH
        text after break
        haha text
  // MATCH
        `Hey,
  // NO
        here is some text!
  // NO
        and here is the end =)`
  // MATCH
        here is text

You can see my example here: https://regex101.com/r/wvrh77/1

How do I match all double new lines, but not those within backticks?

1 Answers

You can use a PCRE-compliant regex like

/`[^`]*`(*SKIP)(*F)|\R{2}/

See the regex demo.

Details:

  • ` - a backtick
  • [^`]* - zero or more chars other than backtick
  • ` - a backtick
  • (*SKIP)(*F) - skip the current match attempt, consider it a fail and start searching for the next match from the failure position
  • | - or
  • \R{2} - two line break sequences.
Related