2014-08-28 55 views
0

我在寻找一个正则表达式,只有当所有大括号正确匹配时才会匹配。匹配大括号可以嵌套。用于匹配大括号的正则表达式

Ex。 相配

  • 你好{0} {}
  • 你好下列{0}:{{Object1}},{{Object2的}}
  • 测试{{1} {{2} {{ 3} {{4}}}}}

非比赛

  • } {你好{0}
  • {{}你好下列{0}:{{Objec T1}},{{Object2的}}
  • 测试{{1} {{2} {{3} {{4} {}
+0

用什么语言?大多数语言不支持嵌套正则表达式匹配,因此您需要使用一组函数来完成此操作。 – 2014-08-28 15:36:27

+0

@ wolffer-east:我在VB中完成它。我希望尽管它可以使用纯正则表达式语法来解决。当你说'最'的时候,这是否意味着有些人会这样做? – 2014-08-28 15:38:44

+0

[可以使用正则表达式来匹配嵌套模式吗?]可能的重复(http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns) – 2014-08-28 15:38:48

回答

2

在.NET可以使用balancing groups来算,它允许解决这些问题。

例如确保{}是平衡的,你可以使用表达式,如:

(?x)^ 
[^{}]* 
(?: 
    (?: 
    (?'open' \{)  # open++ 
    [^{}]* 
)+ 
    (?: 
    (?'close-open' \}) # open--, only if open > 0 
    [^{}]* 
)+ 
)* 
(?(open) (?!))   # fail if open != 0 
$ 
+1

下面是几个更类似的示例:http://stackoverflow.com/questions/15752778/regex-w- balance-group-that-matches-not-only-the-the-most-matches/15753431#15753431 http://stackoverflow.com/questions/17003667/match-text-surrounded-by-and/17003704#17003704 – Qtax 2014-08-28 15:51:03

+0

太棒了!谢谢,我刚刚对我的例子进行了测试,并且它通过了大量的颜色。简直太神奇了。我不明白这一点,所以我想我有一些阅读要做! – 2014-08-28 16:00:08

2
bool BracesMatch(string s) 
{ 
    int numOpen = 0, numClosed = 0; 
    foreach(char c in s.ToCharArray()) 
    { 
    if (c == '{') numOpen++; 
    if (c == '}') numClosed++; 
    if (numClosed > numOpen) return false; 
    } 
    return numOpen == numClosed; 
} 
+0

你有看到这个吗?“if(numClosed> numOpen)返回false;” – Derek 2014-08-28 15:55:11

+2

@Tensibai他检查每个字符上的if(numClosed> numOpen)返回false,所以你的例子没有通过:http://ideone.com/JUkyLZ – nodakai 2014-08-28 16:19:48

+0

我的不好,没有读完。拿我的+1 – Sam 2014-08-28 16:58:42

0

这可能会实现使用点-Net的平衡组为好。

# @"^[^{}]*(?:\{(?>[^{}]+|\{(?<Depth>)|\}(?<-Depth>))*(?(Depth)(?!))\}[^{}]*)*[^{}]*$" 

^ 
[^{}]*      # Anything (but only if we're not at the start of { or }) 
(?: 
     \{       # Match opening { 
     (?>       # Then either match (possessively): 
      [^{}]+      # Anything (but only if we're not at the start of { or }) 
     |        # or 
      \{       # { (and increase the braces counter) 
      (?<Depth>) 
     |        # or 
      \}       # } (and decrease the braces counter). 
      (?<-Depth>) 
    )*       # Repeat as needed. 
     (?(Depth)      # Assert that the braces counter is at zero. 
      (?!)       # Fail this part if depth > 0 
    ) 
     \}       # Then match a closing }. 
     [^{}]*      # Anything (but only if we're not at the start of { or }) 
)*       # Repeat as needed 
[^{}]*      # Anything (but only if we're not at the start of { or }) 
$