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:
- True for out, trout, and pouting
- True for pouting
- 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?
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:
- True for out, trout, and pouting
- True for pouting
- 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?
Share Improve this question asked Jun 7, 2017 at 11:26 JonJon 1192 silver badges8 bronze badges 3- Is it always one word inside brackets, without spaces? – SamWhan Commented Jun 7, 2017 at 11:31
-
Try changing
out\s
toout[a-z0-9 ]
as you can have characters afterout
– Rajesh Commented Jun 7, 2017 at 11:31 - Ah, I was so close! Thanks for your answer, Rajesh! – Jon Commented Jun 7, 2017 at 11:41
1 Answer
Reset to default 6Assuming [...]
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