简体   繁体   中英

How to search regex only outside curly brackets

I have this regex variable:

var regexp = new RegExp(RegExp.quote(myExpression) + '\\b', 'g');

which searches for expression that has a space after it. (RegExp.quate() I got from this How to escape regular expression in javascript? )

I want to search for it only outside curly brackets .

so if I myExpression = "cat"

and I have this string:

the cat { is cat { and } cat {and { another cat } } and  cat } and another cat
    ^^^                                                                    ^^^

I want to get a match only for the first cat and the last cat - I don't want any match for anything inside the outer curly brackets.

I found some regex for this but non of them worked as I hoped for.

what do I need to write to get it done?

thanks, Alon

Something like this problem of matching nested brackets is not possible to solve using a single regex. Here is my take to resolve your problem:

var myExpression = "cat";
var s = 'the cat {is cat { and} cat {and { another cat}}and  cat } and another cat';
arr = s.split(/(?=(?:\b|\W))\s*/g);
document.writeln("<pre>split: " + arr + "</pre>");
//prints: the,cat,{,is,cat,{,and,},cat,{,and,{,another,cat,},},and,cat,},and,another,cat
var level=0;
for (i=0; i<arr.length; i++) {
  if (level == 0 && arr[i] == myExpression)
     document.writeln("<pre>Matched: " + arr[i] + "</pre>");
  if (arr[i] == "{")
     level++;
  else if (arr[i] == "}")
     level--;
}

一种策略是用空字符串查找/替换所有{。*} ...然后查找所有猫?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM