如何仅在大括号外搜索正则表达式 [英] How to search regex only outside curly brackets

查看:88
本文介绍了如何仅在大括号外搜索正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个正则表达式变量:

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--;
}

这篇关于如何仅在大括号外搜索正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆