代码之家  ›  专栏  ›  技术社区  ›  Jeremy Thake MSFT

regex替换查询以选择wiki语法

  •  0
  • Jeremy Thake MSFT  · 技术社区  · 15 年前

    我有一个HTML字符串,我需要获取“[标题 http://www.test.com] ”pattern out of e.g.。

    “达法斯达法斯达夫,阿德法斯。[测试 http://www.test.com/] adf ddasfasdf[sdaf http://www.made.com/] assg ad”,

    我需要用“http://www.test.com/”>title“替换”[标题 http://www.test.com] “this with”http://www.test.com/'>title“。”

    最好的方法是什么?

    我正在接近:

    string test=“dafasdfasdf adfasd[test http://www.test.com/]adf ddasfasdf[sdaf http://www.made.com/]assg ad”;
    字符串p18=@“(\[.*?* *?)
    matchCollection mc18=regex.matches(测试,p18,regexopions.singleline regexopions.ignorecase);
    foreach(匹配mc18中的m)
    {
    字符串值=m.groups[1].值;
    string fullttag=value.substring(value.indexof(“[”),value.length-value.indexof(“[”));
    console.writeline(“text=”+fullttag);
    }
    < /代码> 
    
    

    必须有一种更干净的方法来获取这两个值,例如“标题”位和URL本身。

    有什么建议吗?“例如,

    “达法斯达法斯达夫,阿德法斯。[试验]http://www.test.com/]美国国防部|http://www.made.com/]广告“

    我需要替换“[标题|http://www.test.com]“此文件带有”http://www.test.com/'>标题“。

    最好的方法是什么?

    我正在接近:

    string test = "dafasdfasdf adfasd [Test|http://www.test.com/] adf ddasfasdf [SDAF|http://www.madee.com/] assg ad ";
            string p18 = @"(\[.*?|.*?\])";
            MatchCollection mc18 = Regex.Matches(test, p18, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            foreach (Match m in mc18)
            {
                string value = m.Groups[1].Value;
                string fulltag = value.Substring(value.IndexOf("["), value.Length - value.IndexOf("["));
                Console.WriteLine("text=" + fulltag);
            }
    

    必须有一种更干净的方法来获取这两个值,例如“标题”位和URL本身。

    有什么建议吗?

    1 回复  |  直到 15 年前
        1
  •  2
  •   Bart Kiers    15 年前

    替换图案:

    \[([^|]+)\|[^]]*]
    

    用:

    $1
    

    简短解释:

    \[         # match the character '['
    (          # start capture group 1
      [^|]+    #   match any character except '|' and repeat it one or more times
    )          # end capture group 1
    \|         # match the character '|'
    [^]]*      # match any character except ']' and repeat it zero or more times
    ]          # match the character ']'
    

    C演示如下:

    string test = "dafasdfasdf adfasd [Test|http://www.test.com/] adf ddasfasdf [SDAF|http://www.madee.com/] assg ad ";
    string adjusted = Regex.Replace(test, @"\[([^|]+)\|[^]]*]", "$1");