大括号内内容的正则表达式 [英] regular expression for content within braces

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

问题描述

是否存在正则表达式以匹配括号内的内容。例如,使用以下命令:

is there a regular expression to match the content within braces. For example with the following:

d = {'key': {'a': [1,2,3]}}

我想匹配 {'key':{'a':[1 ,2,3]}} {'a':[1,2,3]} ,但不是 {'key':{'a':[1 ,2,3]}

推荐答案

在经典正则表达式中,这是不可能的-DFA无法解析嵌套

In classical regular expressions, this is impossible - DFAs can't parse nested pairs.

有一些方法可以使用扩展的正则表达式,例如某些regex引擎(例如Perl regex)中允许的递归表达式。并不总是很漂亮。 (太多的PHP 提供了Perl版本: / \ {(?:[^ {}] + |(?R))* \} / ,其中(?R)选项为递归匹配。)

There are ways to do it with extended regular expressions, such as recursive expressions that are allowed in some regex engines (such as Perl regex), but they're not always pretty. (too much php provided the Perl version: /\{(?:[^{}]+|(?R))*\}/ with the (?R) option being the recursive match.)

您不一定需要正则表达式可以做这种事情。您可以简单地通过遍历列表并保留一堆开放的括号(以及它们在什么位置被看到)来做到这一点。然后,每当看到一个开放括号时,就将其位置推入堆栈,每当看到一个封闭括号时,就从堆栈中弹出最近看到的开放括号,并使用其位置加上当前位置作为子字符串的边界。这成为您的比赛之一。重复直到到达字符串的末尾。

You don't necessarily need regex to do this kind of thing though. You could do it simply by walking through the list and keeping a stack of open braces (and what position they were seen at). Then whenever you see an open brace, you push its position onto the stack, and whenever you see a close brace, you pop the most recently seen open brace off the stack, and use its position plus the current position as the bounds for a substring which becomes one of your matches. Repeat until you reach the end of the string.

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

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