Code compiling and running environment Visual Studio 2010. NET v4.0.30319
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Text. RegularExpressions;
Namespace DelegateUseInRegexReplace
{
/// <Summary>
/// Sometimes, use a regular expression to replace part of the matching content in a string.
/// In this example, html source code conversion may occur, that is, you need to replace the domain name or IP address in the href attribute in the hyperlink.
/// In this example, replace the IP address 192.168.1.23 with 202.145.65.15.
/// The delegate MatchEvaluator in regular expression replacement matches a method with a Match parameter to return a string.
/// </Summary> www.2cto.com
Class Program
{
Static void Main (string [] args)
{
String html = "<br/> <a href = \" http: // 192.168.1.23/index.html \ "> 192.168.1.23/index.html </a> ";
Console. WriteLine ("original string :");
Console. WriteLine (html );
String htmlResult = Regex. Replace (html, "<a [^ <] *>", new MatchEvaluator (ReplaceIP ));
Console. WriteLine ("replaced string :");
Console. WriteLine (htmlResult );
}
Public static string ReplaceIP (Match match)
{
Return match. Value. Replace ("192.168.1.23", "202.145.65.15 ");
}
}
}
The running result is:
From gxmark's column