控制平衡的括号 [英] Controlling balanced parenthesis

查看:162
本文介绍了控制平衡的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个包含用圆括号在这方面,我的意思是不同的括号(字符串 [ {)的字符串也可以包含像这样其他内容 {[平衡(括号内)]} ,但内容的其余部分将在很大程度上被忽略是否有可能使用常规的EX pression来控制所有的不同的括号是:

  1. 关闭的,那就是每一个的开放的括号匹配通过的关闭的括号和
  2. 在字符串中正确的位置?
解决方案

事实证明,这个问题已经解决了了Kobi 这篇博客文章< /一他的>。对于简单的平衡不同类型的支架,解决的办法很简单,优雅,而不是疯狂的<一个答案href="http://stackoverflow.com/questions/3349999/converting-pcre-recursive-regex-pattern-to-net-balancing-groups-definition">this问题,其中有一个更复杂的语法。

让我引用下面的博客文章的基本组成部分:

  

[...]谁说我要推我相匹配的协议栈?如果想推动的任意字符串到栈?当我看到一个开放的括号我真的要推右括号 - 但我怎么能

?      

的技巧是使用前瞻:找我要推的字符的下一个出现,然后将其推:

  {(= *(&LT;?。?堆栈&GT;}))
 

     

接下来,当我想匹配一个右括号,我已经有一个正确的堆栈。   使用这种方法,这里是一个正则表达式匹配3种不同的类型化均衡的括号匹配标记:

 (
    [^(){} \ [\] +
    | \((= [^)] *(小于?堆栈&GT; \)))
    | \ [(= [^ \]] *(小于?堆栈&GT; \]))
    | \ {(= [^}] *(小于?堆栈&GT; \}))
    | \ K&LT;栈&GT; (小于?-Stack&GT)
)+&
(?(栈)(?!))
 

     

当然,这种方法也有一定的局限性 - 你可能无法找到的字符,你想推动(这可能是一件好事 - 它可以让你失败年初)。这也得到了,如果你想以平衡东西比常量字符串更加复杂棘手得多,但这是另一个话题。

Assuming we have a string containing different parentheses (by parentheses in this context I mean (, [, and { ) the string could also contain other content like so {[balanced(parenthesis)]} but the rest of the content will largely be ignored. Would it be possible to use regular expression to control that all different parenthesis are:

  1. "closed", that is that each "opening" parenthesis is matched by a "closing" parenthesis, and
  2. at the right position in the string?

解决方案

It turns out this problem has been solved by Kobi in this blog post of his. For simply balancing different types of brackets, the solution is quite simple and elegant, and not as crazy as the answers in this question, which has a more complex grammar.

Let me quote the essential part of the blog post below:

[...] who says I must push what I matched to the stack? What if wanted to push an arbitrary string to the stack? When I see an open bracket I really want to push a closing bracket – but how can I?

The trick is to use a look-ahead: find the next occurrence of the character I want to push, and push it:

{(?=.*?(<Stack>}))

Next, when I want to match a closing brace, I already have the right one in stack. Using this approach, here’s a regex that matches tokens with matching balanced parentheses of 3 different typed:

(
    [^(){}\[\]]+
    | \( (?=[^)]*  (?<Stack> \) ) )
    | \[ (?=[^\]]* (?<Stack> \] ) )
    | \{ (?=[^}]*  (?<Stack> \} ) )
    | \k<Stack> (?<-Stack>)
)+?
(?(Stack) (?!))

Of course, this approach does have limitations – you may not find the character you’d like to push (which might be a good thing – it allows you to fail early). It also gets much trickier if you want to balance something more complicated than constant strings, but that’s another subject.

这篇关于控制平衡的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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