2014-08-28 58 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 }) 
$