代码之家  ›  专栏  ›  技术社区  ›  hacker

替换基于Regex.Matches MatchCollection的字符串中的内容

  •  2
  • hacker  · 技术社区  · 15 年前

    在过去的一天左右,我一直在研究这个正则表达式,我想我已经解决了它,这样它就可以返回我想要的数据。首先是一点背景知识。

    我有一个内容编辑器,用户可以编辑网页。他们可以格式化文本、添加链接等。。标准的内容编辑器。当他们单击save时,编辑器提供了获取内容(editor.content)并将其放入字符串的功能。我想做的是得到任何链接( <a>

    下面是我想到的表达:

    <a\b[^<>]*href\s*=\s*[\""\'](?<domain>https?:\/\/[^\/\s\'\""]*)*\/?(?<path>\/?[^\s\""]+?)?[[>\""\']
    

    有了这个,我就能够分离域(如果有域的话)和路径了。然后,我在比赛中循环。。。

    dim matchColl as MatchCollection = Regex.Matches(editorContent, regExString)
    For Each m as Match in matchColl
       If m.Groups("domain").value <> myInternalDomain and m.Groups("domain").value <> "" then
           'this is an external domain... do some stuff
       End If
       If m.Groups("path").value.EndsWith(".pdf") then
             'it is a pdf, do some other stuff...
       End if
    Next
    

    我的问题是。。。在我对值“做一些事情”的部分,什么是将其返回到我的“editorContent”字符串中的最佳方法?我可能会将editorContent放入StringBuilder并对其进行大量替换,但这是否非常有效?

    任何想法都会很棒!

    谢谢

    1 回复  |  直到 15 年前
        1
  •  3
  •   Andrew Hare    15 年前

    我想你想做一个 Regex.Replace MatchEvaluator . 基本上 是返回替换字符串的函数的委托。