简体   繁体   English

使用C#在字符串中搜索和替换URL

[英]Search and Replace urls within a string using C#

I am loading email messages. 我正在加载电子邮件。 In order to track click throughs, I have replace all occurrences of HREF="http://someurl" with HREF="%%track http://someurl%% " 为了跟踪点击次数,我已将所有出现的HREF =“ http:// someurl”替换为HREF =“ %% track http:// someurl %%

Our email software can then detect the tracking code and track click the clickthroughs (it sees the tracking code and replaces the url with something it can track). 然后,我们的电子邮件软件可以检测到跟踪代码并跟踪点击次数(它会看到跟踪代码,并用可以跟踪的内容替换网址)。 The url can be any valid url. 该网址可以是任何有效的网址。

Does anyone have an example of code to do this type of search and replace? 有没有人有代码示例来执行这种类型的搜索和替换?

thanks 谢谢

The conventional wisdom is that you should not parse HTML with a regular expression. 传统观点认为,您不应使用正则表达式来解析HTML。 However, this case may be simple enough for regex, especially if you have control over the HTML you are receiving and can ensure that the href attribute will always be formatted the same. 但是,这种情况对于正则表达式可能足够简单,尤其是如果您可以控制要接收的HTML,并且可以确保href属性的格式始终相同。

private static readonly Regex hrefRegex =
    new Regex("(?<=href=\")http://[^\"]*(?=\")", RegexOptions.IgnoreCase);

public static string InsertTrackingCode(string html)
{
    return hrefRegex.Replace(html,
        match => "%%track " + match.Groups[0].Value + "%%");
}

Then simply do: 然后只需执行以下操作:

string htmlWithTracking = InsertTrackingCode(htmlWithoutTracking);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM