Jon
Jon

Reputation: 119

Match within string, but ignore matches between brackets - Regex and JavaScript

I have the following string examples:

 "1. go [south], but look out for the trout pouting [lout]"
 "2. go [south], but be wary of the pouting [lout]"
 "3. go [south], but be wary of the sullen-looking [lout]"

I'd like the query word out to match if it appears in each string, but is ignored if it's between brackets. So I'm looking to match:

  1. True for out, trout, and pouting
  2. True for pouting
  3. False

I've managed to get as far as this expression:

/[^\(\)\[\]]out\s(?![\]])/ig

However, it's only matching the first string for out and trout .

I've figured out that the whitespace character is the influencing factor here for not matching pouting, but getting rid of it matches everything between the brackets, too.

What would be the correct regular expression for this?

Upvotes: 4

Views: 3888

Answers (1)

anubhava
anubhava

Reputation: 784948

Assuming [...] are balanced and unescaped, you can use a negative lookahead based search:

/out(?![^\[\]]*\])/

(?![^\[\]]*\]) is a negative lookahead that asserts that we don't have a ] following non-[ and non-] characters ahead thus making sure we're not matching out inside a [...].

Javascript code to build your regex:

search = "out";
var regex = new RexExp(search + "(?![^\\[\\]]*\\])", "g");

RegEx Demo

Upvotes: 6

Related Questions