1

文字列のバランス中括弧({})を一致させようとしています。たとえば、次のバランスを取りたいと思います。

if (a == 2)
{
  doSomething();
  { 
     int x = 10;
  }
}

// this is a comment

while (a <= b){
  print(a++);
} 

私はMSDNからこの正規表現を思いついたが、うまく機能しない。{}のネストされた一致する複数のセットを抽出したいと思います。親の試合にのみ興味があります

   "[^{}]*" +
   "(" + 
   "((?'Open'{)[^{}]*)+" +
   "((?'Close-Open'})[^{}]*)+" +
   ")*" +
   "(?(Open)(?!))";
4

1 に答える 1

6

あなたはかなり近いです。

この質問の2番目の回答から適応(私はそれを私の標準的な「C#/。NET正規表現エンジンでのxxxのバランス調整」の回答として使用し、それがあなたを助けたならそれを賛成します!それは過去に私を助けました):

var r = new Regex(@"
[^{}]*                  # any non brace stuff.
\{(                     # First '{' + capturing bracket
    (?:                 
    [^{}]               # Match all non-braces
    |
    (?<open> \{ )       # Match '{', and capture into 'open'
    |
    (?<-open> \} )      # Match '}', and delete the 'open' capture
    )+                  # Change to * if you want to allow {}
    (?(open)(?!))       # Fails if 'open' stack isn't empty!
)\}                     # Last '}' + close capturing bracket
"; RegexOptions.IgnoreWhitespace);
于 2012-02-06T04:46:17.777 に答える