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:
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With