正则表达式匹配单个括号对但不匹配双括号对

编程入门 行业动态 更新时间:2024-10-10 05:25:45
本文介绍了正则表达式匹配单个括号对但不匹配双括号对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以使正则表达式匹配单括号内的所有内容但忽略双括号,例如在:

Is it possible to make a regular expression to match everything within single brackets but ignore double brackets, so for example in:

{foo} {bar} {{baz}}

我想匹配foo和bar但不是baz?

I'd like to match foo and bar but not baz?

推荐答案

仅匹配 foo 和 bar 没有周围的大括号,你可以使用

To only match foo and bar without the surrounding braces, you can use

(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))

如果您的语言支持lookbehind断言。

if your language supports lookbehind assertions.

说明:

(?<= # Assert that the following can be matched before the current position (?<!\{) # (only if the preceding character isn't a {) \{ # a { ) # End of lookbehind [^{}]* # Match any number of characters except braces (?= # Assert that it's possible to match... \} # a } (?!\}) # (only if there is not another } that follows) ) # End of lookahead

编辑:在JavaScript中,您没有lookbehind。在这种情况下,您需要使用以下内容:

In JavaScript, you don't have lookbehind. In this case you need to use something like this:

var myregexp = /(?:^|[^{])\{([^{}]*)(?=\}(?!\}))/g; var match = myregexp.exec(subject); while (match != null) { for (var i = 0; i < match.length; i++) { // matched text: match[1] } match = myregexp.exec(subject); }

更多推荐

正则表达式匹配单个括号对但不匹配双括号对

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

发布评论

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

>www.elefans.com

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