我有这个正则表达式变量:
var regexp = new RegExp(RegExp.quote(myExpression) + '\\b', 'g');
搜索后面有空格的表达式。 (RegExp.quate() 我从这个 How to escape regular expression in javascript? 得到的)
我只想在大括号之外搜索它。
所以如果我myExpression = "cat"
我有这个字符串:
the cat { is cat { and } cat {and { another cat } } and cat } and another cat
^^^ ^^^
我只想为第一只猫和最后一只猫获得匹配 - 我不希望与外部大括号内的任何内容匹配。
我为此找到了一些正则表达式,但没有一个像我希望的那样工作。
我需要写什么才能完成它?
谢谢, 阿隆
最佳答案
像匹配嵌套括号这样的问题是不可能使用单个正则表达式来解决的。以下是我解决您问题的方法:
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--;
}
关于javascript - 如何仅在大括号之外搜索正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9420048/