一分钟学会(一):.NET之正则表达式

本文介绍正则表达式在.NET中的基本应用,代码简单粗暴,实例浅显易懂,让你一分钟快速上手正则(大鸟请略过)。

本文为入门文章,很多时候我们只是忘记了语法,这也可作为一个快速查询的参考。 如果想深入学习正则表达式高级功能请参考其他资料

=========首先引入命名空间 using System.Text.RegularExpressions;

//1.查找
        static void Test1()
        {
            Console.WriteLine("=========Match方法匹配第一个===========");
            Regex regex = new Regex(@"d{3}"); //@ 表示不用进行转义 在.NET中是转义符 此表达式等同于 \d{3}
            Match m = regex.Match("this is an apple 123 456 9999");
            Console.WriteLine(m);

            Console.WriteLine("=========Matches方法匹配所有===========");
            MatchCollection matches = regex.Matches("this is an apple 123 456 9999");
            foreach(Match match in matches)
            {
                Console.WriteLine(match);
            }

            Console.WriteLine("=========IsMatch检查匹配是否成功===========");
            bool result = regex.IsMatch("this is an apple 123 456 9999");
            Console.WriteLine(result);
        }

 结果:=========

------------------------------------------------------------------------------------------------------------

//2.替换操作
        static void Test2()
        {
            //替换所有匹配项
            Regex regex = new Regex("apple");
            string result = regex.Replace("this is an apple,apple,apple", "苹果");
            Console.Write(result);
        }

  结果:=========

------------------------------------------------------------------------------------------------------------

 //3.使用委托
        static void Test3() 
        {
            string result = Regex.Replace("1 2 3 4 5",@"d+", new MatchEvaluator(
                delegate(Match match) {//匿名方法
                    return "0" + match.Value;
                }
            ),RegexOptions.IgnoreCase|RegexOptions.Singleline);
            //最后一个参数匹配模式 可选
            Console.WriteLine(result);
        }

  结果:=========

简单说明一下,Replace方法可以传入一个委托,对匹配结果自定义处理,new MatchEvaluator(delegate),delegate为方法名,Match作为参数传入, 这里使用了匿名方法。

------------------------------------------------------------------------------------------------------------

 //4.$number 使用表达式替换匹配结果中的 number 组  $1表示组1匹配的结果
        static void Test4()
        {
            string result = Regex.Replace("1 2 3 12 13", @"(d)(d)", "A$1");
            Console.WriteLine(result);
        }

上面的正则表达式有两个分组 (d) 和 (d) 匹配结果如下图所示

Replace方法第三个参数 A$1 中的$1 表示使用 匹配结果中Group_1 的值 替换 字符串中所有匹配项 所以 A1替换 12 ,A1替换13 结果如下

如果参数换为 abc$2  表示使用匹配结果中 Group_2 的值 替换字符串中所有匹配项 所以 abc2替换 12 ,abc3替换13 结果如下

此处比较绕口,实在不明白请自行敲一下代码。

------------------------------------------------------------------------------------------------------------

//5.${name} 使用表达式替换匹配结果中的 name 组  ${name}表示组名为name匹配的结果 ?<name> 给改组命名为name
        static void Test5() {
            string result = Regex.Replace("1 2 3 12 13", @"(d)(?<name>d)", "A${name}");
            Console.WriteLine(result);
        
        }
        //补充
        //$$ $转义符
        //$& 替换整个匹配
        //$^ 替换匹配前的字符
        //$' 替换匹配后的字符
        //$+ 替换最后匹配的组
        //$_ 替换整个字符串
        //(?#这个是注释)  正则内联注释语法 (?#注释)

 给分组命名使用  ?<name> 如下图 命名以后Group_2 的组名为:name ,${name} 和上一节的$1类似 一个用编号引用 一个用名字引用

------------------------------------------------------------------------------------------------------------

//6.1分组
        static void Test6() 
        {
            string s = "2005-2-21";
            Regex reg = new Regex(@"(?<y>d{4})-(?<m>d{1,2})-(?<d>d{1,2})", RegexOptions.Compiled);
            Match match = reg.Match(s);

            int year = int.Parse(match.Groups["y"].Value);
            int month = int.Parse(match.Groups["m"].Value);
            int day = int.Parse(match.Groups["d"].Value);

            DateTime time = new DateTime(year, month, day);
            Console.WriteLine(time);
            Console.ReadLine();

            //DateTime.Parse(s);
        }

 上面的代码可以用 DateTime.Parse(s) 实现,这里为了展示如何给分组命名和取值 

=========

//6.2
        static void Test7()
        {
            string s = "2005-2-21";
            Regex reg = new Regex(@"(d{4})-(d{1,2})-(d{1,2})", RegexOptions.Compiled);
            Match match = reg.Match(s);

            int year = int.Parse(match.Groups[1].Value);
            int month = int.Parse(match.Groups[2].Value);
            int day = int.Parse(match.Groups[3].Value);

            DateTime time = new DateTime(year, month, day);
            Console.WriteLine(time);
            Console.ReadLine();
        }

 未命名的分组可以直接用编号取得 Groups[1],Groups[2],Groups[3]

=======

//6.3
        static void Test8()
        {
            string s = "2005-2-21";
            Regex reg = new Regex(@"(?<2>d{4})-(?<1>d{1,2})-(?<3>d{1,2})", RegexOptions.Compiled);
            Match match = reg.Match(s);

            int year = int.Parse(match.Groups[2].Value);
            int month = int.Parse(match.Groups[1].Value);
            int day = int.Parse(match.Groups[3].Value);

            DateTime time = new DateTime(year, month, day);
            Console.WriteLine(time);
            Console.ReadLine();
        }

 Groups[2] 这里的 2代表的是名字 而不是编号

===========================================================================

看到这里相信你对.NET中如何使用正则有了一个基本的认识, Regex类提供了很多静态的方法可以直接调用,很多时候可以不需要实例化。

//全部代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Text.RegularExpressions;
namespace demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Test6();

            Console.ReadLine();
        }


        //1.查找
        static void Test1()
        {
            Console.WriteLine("=========Match方法匹配第一个===========");
            Regex regex = new Regex(@"d{3}"); //@ 表示不用进行转义 在.NET中是转义符 此表达式等同于 \d{3}
            Match m = regex.Match("this is an apple 123 456 9999");
            Console.WriteLine(m);

            Console.WriteLine("=========Matches方法匹配所有===========");
            MatchCollection matches = regex.Matches("this is an apple 123 456 9999");
            foreach(Match match in matches)
            {
                Console.WriteLine(match);
            }

            Console.WriteLine("=========Matches方法匹配所有===========");
            bool result = regex.IsMatch("this is an apple 123 456 9999");
            Console.WriteLine(result);
        }

        //2.替换操作
        static void Test2()
        {
            //替换所有匹配项
            Regex regex = new Regex("apple");
            string result = regex.Replace("this is an apple,apple,apple", "苹果");
            Console.Write(result);
        }

        //3.使用委托
        static void Test3() 
        {
            string result = Regex.Replace("1 2 3 4 5",@"d+", new MatchEvaluator(
                delegate(Match match) {//匿名方法
                    return "0" + match.Value;
                }
            ),RegexOptions.IgnoreCase|RegexOptions.Singleline);
            //最后一个参数匹配模式 可选
            Console.WriteLine(result);
        }

        //4.$number 使用表达式替换匹配结果中的 number 组  $1表示组1匹配的结果
        static void Test4()
        {
            string result = Regex.Replace("1 2 3 12 13", @"(d)(d)", "A$1");
            Console.WriteLine(result);
        }

        //5.${name} 使用表达式替换匹配结果中的 name 组  ${name}表示组名为name匹配的结果 ?<name> 给改组命名为name
        static void Test5() {
            string result = Regex.Replace("1 2 3 12 13", @"(d)(?<name>d)", "A${name}");
            Console.WriteLine(result);
        
        }
        //补充
        //$$ $转义符
        //$& 替换整个匹配
        //$^ 替换匹配前的字符
        //$' 替换匹配后的字符
        //$+ 替换最后匹配的组
        //$_ 替换整个字符串
        //(?#这个是注释)  正则内联注释语法 (?#注释)

        //6.1分组
        static void Test6() 
        {
            string s = "2005-2-21";
            Regex reg = new Regex(@"(?<y>d{4})-(?<m>d{1,2})-(?<d>d{1,2})", RegexOptions.Compiled);
            Match match = reg.Match(s);

            int year = int.Parse(match.Groups["y"].Value);
            int month = int.Parse(match.Groups["m"].Value);
            int day = int.Parse(match.Groups["d"].Value);

            DateTime time = new DateTime(year, month, day);
            Console.WriteLine(time);
            Console.ReadLine();

            //DateTime.Parse(s);
        }

        //6.2
        static void Test7()
        {
            string s = "2005-2-21";
            Regex reg = new Regex(@"(d{4})-(d{1,2})-(d{1,2})", RegexOptions.Compiled);
            Match match = reg.Match(s);

            int year = int.Parse(match.Groups[1].Value);
            int month = int.Parse(match.Groups[2].Value);
            int day = int.Parse(match.Groups[3].Value);

            DateTime time = new DateTime(year, month, day);
            Console.WriteLine(time);
            Console.ReadLine();
        }

        //6.3
        static void Test8()
        {
            string s = "2005-2-21";
            Regex reg = new Regex(@"(?<2>d{4})-(?<1>d{1,2})-(?<3>d{1,2})", RegexOptions.Compiled);
            Match match = reg.Match(s);

            int year = int.Parse(match.Groups[2].Value);
            int month = int.Parse(match.Groups[1].Value);
            int day = int.Parse(match.Groups[3].Value);

            DateTime time = new DateTime(year, month, day);
            Console.WriteLine(time);
            Console.ReadLine();
        }

    }
}
View Code
原文地址:https://www.cnblogs.com/gosky/p/4065530.html