用于匹配花括号的正则表达式

时间:2014-08-28 15:34:28

标签: .net regex vb.net

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

实施例。 匹配

  • 您好{0} {}
  • 您好以下{0}:{{Object1}},{{Object2}}
  • 测试{{1} {{2} {{3} {{4}}}}}

非匹配

  • } {Hello {0}
  • {{}您好以下{0}:{{Object1}},{{Object2}}
  • 测试{{1} {{2} {{3} {{4} {}

3 个答案:

答案 0 :(得分:2)

在.NET中,您可以使用balancing groups进行计数,这样可以解决此类问题。

例如,确保{}均衡,您可以使用以下表达式:

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

答案 1 :(得分: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;
}

答案 2 :(得分:1)

这也可以使用Dot-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 } )
 $ 
相关问题