【问题标题】:How to replace a url having brackets with hyperlink/anchor tag in the text C#如何在文本C#中用超链接/锚标记替换带有括号的url
【发布时间】:2019-02-27 02:26:54
【问题描述】:

我正在尝试用锚标记替换所有出现的 URL。 我可以对大多数 URL 字符执行此操作,但是当 URL 中有 () 时,代码会中断。

例如。

https://example.com/Heavy-Industry/Global-Perfluorosulfonic-Acid-(PFSA)-Market-Status-By-Manufacturers,-Types-And-Application,-History-And-Forecast-2025#sample

这是我的代码:

protected string MakeLink(string text)
{
    string text2 = Regex.Replace(text,
        @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)",
        "<a target='_blank' href='$1'>$1</a>");

    return text2;
}

【问题讨论】:

    标签: c# regex winforms


    【解决方案1】:

    你应该将括号添加到字符类[\w\-.,@?^=%&amp;amp;:/~+#()]

    如果您不使用捕获组,我认为您可以通过使用单个捕获组进行替换来使您的正则表达式更加紧凑。

    请注意,您不必在字符类中转义点和加号。

    ((?:https?|ftp):\/\/[\w\-_]+(?:\.[\w\-_]+)+(?:[\w\-.,@?^=%&amp;amp;:/~+#()]*[\w\-@?^=%&amp;amp;/~+#])?)

    Regex demo | Demo C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 2020-02-06
      • 2019-04-12
      相关资源
      最近更新 更多