2011-03-17 181 views
2

我想問一下C#中的正則表達式。正則表達式在大括號之間得到字符串

我有一個字符串。例如:{{歡迎使用{stackoverflow}}這是一個問題C#}「

關於正則表達式在{}之間獲取內容的任何想法。我想得到2字符串是:「歡迎來到stackoverflow。這是一個問題C#」和「stackoverflow」。

感謝提前和對我的英語感到抱歉。

+0

你想限制自己只有兩個{,或無限級別的水平?所以{{{{{{Hello}}}}}} – xanatos 2011-03-17 10:48:59

回答

0

謝謝大家。我有解決方案。我使用堆棧而不是正則表達式。我推動「{」堆棧,當我遇到「}」時,我會彈出「{」並獲得索引。從該索引獲得字符串到索引「}」後。再次感謝。

0

ve written a little RegEx, but haven牛逼測試,但你可以嘗試這樣的:

Regex reg = new Regex("{(.*{(.*)}.*)}"); 

...並建立起來就可以了。

1

嗨不知道怎麼做,用一個正則表達式,但它會增加一點點遞推簡單:

using System; 
using System.Collections.Generic; 
using System.Text.RegularExpressions; 

static class Program { 

    static void Main() { 
     string test = "{Welcome to {stackoverflow}. This is a question C#}"; 
     // get whatever is not a '{' between braces, non greedy 
     Regex regex = new Regex("{([^{]*?)}", RegexOptions.Compiled); 
     // the contents found 
     List<string> contents = new List<string>(); 
     // flag to determine if we found matches 
     bool matchesFound = false; 
     // start finding innermost matches, and replace them with their 
     // content, removing braces 
     do { 
      matchesFound = false; 
      // replace with a MatchEvaluator that adds the content to our 
      // list. 
      test = regex.Replace(test, (match) => { 
       matchesFound = true; 
       var replacement = match.Groups[1].Value; 
       contents.Add(replacement); 
       return replacement; 
      }); 
     } while (matchesFound); 
     foreach (var content in contents) { 
      Console.WriteLine(content); 
     } 
    } 

} 
相關問題