我有这个正则表达式变量:
I have this regex variable:
var regexp = new RegExp(RegExp.quote(myExpression) + '\\b', 'g');会搜索后面有空格的表达式. (RegExp.quate(),我从此中获得了如何在javascript中转义正则表达式? )
which searches for expression that has a space after it. (RegExp.quate() I got from this How to escape regular expression in javascript?)
我只想在大括号之外搜索.
所以如果我myExpression = "cat"
我有这个字符串:
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?
谢谢, 阿隆
推荐答案使用单个正则表达式无法解决类似嵌套括号匹配的问题.这是我为您解决问题的方法:
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--; }更多推荐
如何仅在大括号外搜索正则表达式
发布评论