2015-09-10 111 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

相关问题