How to search regex only outside curly brackets

前端 未结 2 1632
星月不相逢
星月不相逢 2021-01-26 09:12

I have this regex variable:

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

which searches for expression that has a sp

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-26 09:53

    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("
    split: " + arr + "
    "); //prints: the,cat,{,is,cat,{,and,},cat,{,and,{,another,cat,},},and,cat,},and,another,cat var level=0; for (i=0; iMatched: " + arr[i] + "
    "); if (arr[i] == "{") level++; else if (arr[i] == "}") level--; }

提交回复
热议问题