Golden_flash
Golden_flash

Reputation: 492

Match anywhere except between double square brackets

I'm trying to match a pattern except when the match appears in between double square brackets.

The pattern I'm trying to match is \|, i.e. the | character.

Example:

Val 1 | Val 2 | Val3

This will return 2 matches. However, I want to skip | char if it is inside [[...]]. Example:

Val 1 | [[ | ]] | Val 3

Here I do not want the | char inside [[ ]] to be returned.Therefore this should return 2 matches.

I tried negative lookhead but my regex doesn't seem to work.

I captured [[ | ]] using \[\[.*\|.*\]\]:

[^(\[\[.*\|.*\]\])]
(?!(\[\[.*\|.*\]\]))

Those don't seem to give me the desired result.

Upvotes: 2

Views: 110

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

Use a SKIP-FAIL technique:

\[\[.*?]](*SKIP)(*FAIL)|\|

See the regex demo

Details

  • \[\[.*?]](*SKIP)(*FAIL) - matches [[, then any 0+ chars, as few as possible, other than line break chars (add /s modifier to match across lines) and then ]], and then the (*SKIP)(*FAIL) (or (*SKIP)(*F) or (*SKIP)(?!)) will omit the match and will make the regex engine proceed to search for another | from the end of the current match
  • | - or
  • \| - a literal | pipe symbol

Upvotes: 1

Related Questions