最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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?

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?

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 to out[a-z0-9 ] as you can have characters after out – 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
Add a ment  | 

1 Answer 1

Reset to default 6

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

发布评论

评论列表(0)

  1. 暂无评论