Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
Jon Avatar asked Oct 22 '25 14:10

Jon


1 Answers

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

like image 123
anubhava Avatar answered Oct 24 '25 04:10

anubhava