如何仅在大括号外搜索正则表达式

编程入门 行业动态 更新时间:2024-10-26 05:21:09
本文介绍了如何仅在大括号外搜索正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

如何仅在大括号外搜索正则表达式

本文发布于:2023-11-03 12:23:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555125.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!