简体   繁体   中英

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%% "

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. 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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