C # regular function matching, substitution, extraction usage code sharing

Source: Internet
Author: User
Tags expression engine
This article mainly introduced the C # regular function usage, combined with the example form Analysis C # based on regular matching, substitution, extraction of related operations skills, the need for friends can refer to the following

The examples in this article describe the use of C # regular functions. Share to everyone for your reference, as follows:

The System.Text.RegularExpressions namespace contains classes that provide access to the. NET Framework regular expression engine. This namespace provides regular expression functionality that can be used from any platform or language running within the Microsoft. NET Framework.

1 common uses of regular expressions

① format Matching

<summary>///mailbox Format Validation///</summary>///<returns></returns>public static string Checkmail ( String stremail) {  string result = "";  Regex regex = new Regex (@ "[a-za-z0-9._%-]+@[a-za-z0-9.-]+\.[ a-za-z]{2,4} ");  Match match = regex. Match (stremail);  if (match. Success)  {    result = Stremail;  }  else  {    result = "Invalid mailbox";  }  return result;}

② Replacing matching content

<summary>///Convert date format (yyyy-mm-dd to yyyy MM month DD day)///</summary>///<param name= "Strdate" ></param >///<returns></returns>public static string TransDate (String strdate) {  string result = "";  Regex regex = new Regex (@ "(\d+)-(\d+)-(\d+)");  if (regex. IsMatch (strdate))  {    result = regex. Replace (Strdate, "$ $-month-$-day");  }  return result;}

③ Extract Matching content

<summary>///Regular expression extract and replace content//</summary>public static string Contentextract () {  string result = ""; c1/>string str = "Hello everyone!" <user entrytime= ' 2010-10-7 ' email= ' zhangsan@163.com ' > Zhang San </User> self Introduction. ";  Regex regex = new Regex (@ "<user\s*entrytime=" (? <time>[\s\s]*?) ' \s+email= ' (? <email>[\s\s]*?) ' > (? <username>[\s\s]*?) </User> ", regexoptions.ignorecase);  Match match = regex. Match (str);  if (match. Success)  {    string userName = match. groups["UserName"]. Value; Gets the user name    string time = match. groups["Time"]. Value; Get onboarding time    string email = match. groups["Email"]. Value; Get the mailbox address    string strformat = String.Format ("I am: {0}, Entry time: {1}, mailbox: {2}", UserName, time, email);    result = Regex. Replace (str, strformat); Replace content    Console.WriteLine (result);  }  return result;  Result: Hello everyone! I am Zhang San, entry time: 2010-10-7, e-mail: zhangsan@163.com self-introduction. }

2 One instance of me

<summary>///extracts the matching fields from the XML///</summary>///<param name= "args" ></param>static void Main ( String[] args) {string strxml = Getstrxml ();//create User information XML regex Userregex = new Regex (@ "<user\s*entrytime=" (? <time& Gt [\s\s]*?) ' \s+email= ' (? <email>[\s\s]*?) ' > (? <username>[\s\s]*?)  </User> ", regexoptions.ignorecase);  MatchCollection usermatchcoll = userregex.matches (strxml); if (Usermatchcoll.count > 0) {foreach (Match matchitem in Usermatchcoll) {string userName = Matchitem.gro ups["UserName"]. Value; Gets the user name string time = TransDate (matchitem.groups["Time"). Value); Get the onboarding time and convert the date format to string email = checkmail (matchitem.groups["email"). Value);      Get the email address and detect the mailbox format string Strformat = String.Format ("name: {0}, Entry time: {1}, mailbox: {2}", UserName, time, email);    Console.WriteLine (Strformat); }} console.readline ();} <summary>///Creating user information xml///</summary>///<returns></returns>public static string GetStrXmL () {StringBuilder strxml = new StringBuilder ();  Strxml.append ("<UserInfo>");  Strxml.append ("<user entrytime= ' 2010-10-7 ' email= ' zhangsan@163.com ' > Zhang San </User>");  Strxml.append ("<user entrytime= ' 2012-5-15 ' email= ' lisi163.com ' > John Doe </User>");  Strxml.append ("<user entrytime= ' 2012-6-13 ' email= ' wangwu@qq.com ' > Harry </User>");  Strxml.append ("</UserInfo>"); return strxml.tostring ();}
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.