Use code to learn C # & amp;. NET -- delegate usage (Regular Expression replacement)

Source: Internet
Author: User

 

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.