2015-09-10 104 views
1

事實是,我有一個很難寫的正則表達式的字符串進行解析東西的正則表達式中的正則表達式?

[[[tab name=dog content=cat|tab name=dog2 content=cat2]]] 

此正則表達式的形式將被解析,這樣我可以動態地構建標籤爲這​​裏展示。最初我嘗試了一個像\[\[\[tab name=(?'name'.*?) content=(?'content'.*?)\]\]\]

正則表達式模式但我意識到我無法得到整個選項卡,並建立在查詢沒有做regex.replace。是否有可能將整個選項卡作爲一個組採用管道符號,然後從子鍵/值對中解析該組?

這是當前正則表達式字符串我與\[\[\[(?'tab'tab name=(?'name'.*?) content=(?'content'.*?))\]\]\]

工作,這是我的執行正則表達式的代碼。任何指導將不勝感激。

public override string BeforeParse(string markupText) 
    { 
     if (CompiledRegex.IsMatch(markupText)) 
     { 
      // Replaces the [[[code lang=sql|xxx]]] 
      // with the HTML tags (surrounded with {{{roadkillinternal}}. 
      // As the code is HTML encoded, it doesn't get butchered by the HTML cleaner. 
      MatchCollection matches = CompiledRegex.Matches(markupText); 
      foreach (Match match in matches) 
      { 
       string tabname = match.Groups["name"].Value; 
       string tabcontent = HttpUtility.HtmlEncode(match.Groups["content"].Value); 
       markupText = markupText.Replace(match.Groups["content"].Value, tabcontent); 

       markupText = Regex.Replace(markupText, RegexString, ReplacementPattern, CompiledRegex.Options); 
      } 
     } 

     return markupText; 
    } 
+0

你的真實世界中有更多的數據,你的例子沒有提供足夠的複雜性嗎? – OmegaMan

回答

0

這是你想要的嗎?

string input = "[[[tab name=dog content=cat|tab name=dog2 content=cat2]]]"; 
Regex r = new Regex(@"tab name=([a-z0-9]+) content=([a-z0-9]+)(\||])"); 

foreach (Match m in r.Matches(input)) 
{ 
    Console.WriteLine("{0} : {1}", m.Groups[1].Value, m.Groups[2].Value); 
} 

http://regexr.com/3boot

0

也許string.split會在這種情況下更好?例如類似的東西:

strgin str = "[[[tab name=dog content=cat|tab name=dog2 content=cat2]]]"; 
foreach(var entry in str.Split('|')){ 
var eqBlocks = entry.Split('='); 
var tabName = eqBlocks[1].TrimEnd(" content"); 
var content = eqBlocks[2]; 
} 

醜陋的代碼,但應該工作。

0

正則表達式模式,就像提煉下降到只有個別片圖案如name=??? content=???和匹配。該模式將使每個Match(例如兩個)可以提取數據的位置。

string text = @"[[[tab name=dog content=cat|tab name=dog2 content=cat2]]]"; 
string pattern = @"name=(?<Name>[^\s]+)\scontent=(?<Content>[^\s|\]]+)"; 

var result = Regex.Matches(text, pattern) 
        .OfType<Match>() 
        .Select(mt => new 
        { 
         Name = mt.Groups["Name"].Value, 
         Content = mt.Groups["Content"].Value, 
        }); 

結果是可枚舉列表與所需要的選項卡中的創建的動態實體可以被直接結合到控制:

enter image description here


注意,在該組符號[^\s|\]]的管道|被視爲集合中的文字,並未用作or。儘管被視爲文字,但是]確實必須被轉義。最後,解析將查找的邏輯爲:「對於該集合,」而不是^)是spacepipebrace

+0

謝謝你的回答,迄今爲止它工作得很好。你能提供一個你如何將這個結果用於Regex Replace中的例子嗎? – Kyle

+0

@Kyle,你可以添加到你的文章,給出數據應該看起來像什麼之前和之後?目前還不清楚這個問題是第一個正則表達式還是替換。謝謝 – OmegaMan

相關問題