C#_正则表达式


正则表达式是一组由字母和符号组成的特殊文本,它可以用来从文本中找出满足你想要的格式的句子。 通俗的讲就是按照某种规则去匹配符合条件的字符串

正则表达式的用途:

  • 表单输入验证。
  • 搜索和替换。
  • 过滤大量文本文件(如日志)中的信息。
  • 读取配置文件。
  • 网页抓取。
  • 处理具有一致语法的文本文件,

正则初识

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _03正则初识
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string s = "fshkd45794587hasdfisdh8947859?>中文";

            //输出所有的数字


            for (int i = 0; i < s.Length; i++) {
                if (s[i] >= '0' && s[i]<='9')
                {
                    Console.WriteLine(s[i]);
                }
            }

            Console.WriteLine(Regex.Matches(s,@"\d"));
            
            foreach(var item in Regex.Matches(s, @"\d"))
            {
                Console.WriteLine(item);
            }


        }
    }
}

创建正则

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _04创建正则
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //字符串可以使用@""进行创建,这种字符串的内容将会忽略转义字符并且保留格式,写什么就是什么
            //正则表达式就是一个字符串,只是他是用字符串表示一种匹配模式, \d 匹配数字的模式  \w 匹配单词的模式  ....
            //因为正则中需要使用 \x的模式,因此不能使用普通的字符串创建方式,程序会认识\x是一种转义,所以一般都是使用@""
            string s1 = "aaa\nbbb";//换行
            Console.WriteLine(s1);
            string s2 = @"aaa\nbbb";//\n
            Console.WriteLine(s2);



            string string1 = "123abc123abcacbd";

            //正则表达式是由许多子表达式构建的,一个子表达式表示一种规则
            //1.创建一个正则表达式
            Regex reg1 = new Regex(@"a");//匹配字符a
            //2.可以使用Replace方法进行替换正则匹配到的字符
            //正则表达式对象的方法Replace用于替换字符,返回替换后的字符串
            Console.WriteLine(reg1.Replace(string1,"*"));//123*bc123*bc*cd

            //这个正则中包含两个子表达式,分别为a和b,表示匹配字符a和字符b,并且必须相邻
            Regex reg2 = new Regex(@"ab");
            Console.WriteLine(reg2.Replace(string1, "*"));//23*c123*cacbd

            //正则表达式中的普通字符,些什么就是什么,有些字符比较特殊,需要使用\进行转义
            //如: \ . * [] () {}...

            string string2 = "这是一个杠:\\,这是一个点 . 这是一个星号*";
            Console.WriteLine("源字符串:"+string2);

            //正则表达式中  \ 表示转义  如果需要匹配 \  需要写 \\
            Regex reg3 = new Regex(@"\\");
            Console.WriteLine(reg3.Replace(string2, "%"));

            Regex reg4 = new Regex(@"\.");
            Console.WriteLine(reg4.Replace(string2, "%"));
            Regex reg5 = new Regex(@"\*");
            Console.WriteLine(reg5.Replace(string2, "%"));




            string string3 = "123\n新的一行\t一个tab,一个警告提示音 \a";
            Console.WriteLine("源字符串"+string3);

            //还有一些特殊的 \x  表示特殊的含义

            // \a 匹配字符串中的\a
            // \t 匹配字符串中的\t
            // \n 匹配字符串中的\n

            Regex reg6 = new Regex(@"\a");
            Console.WriteLine(reg6.Replace(string3,"%"));

            Regex reg7 = new Regex(@"\t");
            Console.WriteLine(reg7.Replace(string3, "%"));

            Regex reg8 = new Regex(@"\n");
            Console.WriteLine(reg8.Replace(string3, "%"));
            Console.WriteLine("----------------------");



            //string4 使用的是@"" 其中的\t就是\t 不表示缩进 因此正则中的\t也不能匹配到
            //正则中需要使用\\t进行转义,表示真正的\t字符串 而不是缩进
            string string4 = @"123\n新的一行\t一个tab,一个警告提示音 \a";
            reg8 = new Regex(@"\\n");
            Console.WriteLine(reg8.Replace(string4, "%"));


        }
    }
}

字符类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _05字符类
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 上个课件中的子表达式 一个字符就表示匹配固定的那一个字符
            // 字符类与一组字符中任何一个字符匹配

            string s1 = "12sfdsf3243241212212sdfasd233";
            Regex reg1 = new Regex(@"12");//匹配1和2
            Console.WriteLine(reg1.Replace(s1,"*"));
           //[213abc] 匹配[]中所有的字符中的任意一个
            Regex reg2 = new Regex(@"[12]");//匹配1或者2
            Console.WriteLine(reg2.Replace(s1, "*"));

            Regex reg3= new Regex(@"[12s]");//匹配1或者2或者s
            Console.WriteLine(reg3.Replace(s1, "*"));

            //[^12] 匹配除了12之外的所有的字符
            Regex reg4 = new Regex(@"[^12]");//
            Console.WriteLine(reg4.Replace(s1, "*"));




            string s2 = "qrewrewrLHIGHGUYUG21234567890中文";

            //[c-j] 匹配c到j之间的所有的小写字母
            Regex reg5 = new Regex(@"[c-j]");
            Console.WriteLine(reg5.Replace(s2, "*"));

            //[C-J] 匹配c到j之间的所有的大写字母
            Regex reg6 = new Regex(@"[C-J]");
            Console.WriteLine(reg6.Replace(s2, "*"));
            //[C-Jc - j] 匹配大写字母c-j或者小写字母c-j
            Regex reg7 = new Regex(@"[C-Jc-j]");
            Console.WriteLine(reg7.Replace(s2, "*"));

            //[A-Za-z] 匹配大小写字母
            Regex reg8 = new Regex(@"[A-Za-z]");
            Console.WriteLine(reg8.Replace(s2, "*"));
             //匹配中文字符
            Regex reg9 = new Regex(@"[\u4e00-\u9fa5]");
            Console.WriteLine(reg9.Replace(s2, "*"));


            string s3 = "123abc中国字\n换行测试";


            Regex reg10 = new Regex(@".");
            // . 除了 \n换行之外的任意字符
            Console.WriteLine(reg10.Replace(s3, "*"));

            string s4 = "123abc中自耦福阿奴&*(&*^^&*^*国字\n换行测试";
            //\w任何单词字符
            Regex reg11 = new Regex(@"\w");//字母 数字 下划线,.....
            // . 除了 \n换行之外的任意字符
            Console.WriteLine(reg11.Replace(s4, "*"));


            //  \w 任何单词字符
            //  \W 任何非单词字符
            //  \s 空白字符 包含空格 \t \n \f \v
            //  \S 非空白父组 不包含空格 \t \n \f \v
            //  \d 数字
            //  \D 非数字



        }
    }
}

限定符

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _06限定符
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string s1 = "a aa aaa b bb bbb aaaa";

            Regex reg1 = new Regex(@"aaa");
            Console.WriteLine(reg1.Replace(s1,"*"));


            //使用限定符可以很方便的控制子表达式出现的次数

            Regex reg2= new Regex(@"a{3}");//匹配 aaa
            Console.WriteLine(reg2.Replace(s1, "*"));



            string s2 = "a aa aaa b bb bbb  aaaa ab ac";
            Regex reg3 = new Regex(@"[ab]{2}");// a或者b出现2次 aa bb ab ba
            Console.WriteLine(reg3.Replace(s2, "*"));

            string s3 = "1 12 123 1234 12345 123456";

            //{m,} 前面一个子表达式必须至少出现m次  最多不限制
            Regex reg4 = new Regex(@"\d{3,}");// 
            Console.WriteLine(reg4.Replace(s3, "*"));

            //{m,n} 前一个子表达式必须至少出现m次, 最多出现n次
            Regex reg5 = new Regex(@"\d{3,5}");// 
            Console.WriteLine(reg5.Replace(s3, "*"));

            // * 前一个子表达式必须至少出现0次,最多不限制  等价于{0,}
            // + 前一个子表达式必须至少出现1次,最多不限制  等价于{1,}
            // ? 前一个子表达式必须至少出现0次,最多1次  等价于{0,1}


            //非贪婪匹配
            //默认正则表达式以贪婪模式进行查询,也就是说会尽量多的匹配满足条件的字符
            string s4 = "1 12 123 1234 12345 123456";

            Regex reg6 = new Regex(@"\d{3,}");// 将会匹配123 1234 12345 123456
            Console.WriteLine(reg6.Replace(s4, "*")); //1 12 * * * *

            //我们可以在量词的后面加上一个? 修改这个量词为非贪婪模式查询,会尽可能少的匹配字符
            Regex reg7 = new Regex(@"\d{3,}?");//  123 123  123 456
            Console.WriteLine(reg7.Replace(s4, "*")); //1 12 * *4 *45 **

        }
    }
}

定位点

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _07定位点
{
    internal class Program
    {
        static void Main(string[] args)
        {

            string s = "32ab12bc";

            // ^  写在正则表达式的最前面 表示以"后一个表达式"开头或者为行的开头(开启正则表达式的多行匹配模式)
            Regex regex = new Regex(@"^\d");
            Console.WriteLine(regex.Replace(s,"*"));

            
            s = "acb12";
            regex=new Regex(@"^[a-z]{3}"); //必须以三个小写字母开头
            Console.WriteLine(regex.Replace(s, "*"));

            //$ 写在正则表达式的最后面 表示以"前一个表达式"结尾或者为行的结尾(开启正则表达式的多行匹配模式)
            s = "abcbc";
            regex = new Regex(@"c$");
            Console.WriteLine(regex.Replace(s, "*"));

            s = "abcbc";
            regex = new Regex(@"[a-z]{3}$");
            Console.WriteLine(regex.Replace(s, "*"));

            //^ 和 $ 默认只匹配单行的开头和结尾
            s = "abc\nabc";
            regex = new Regex(@"^a");
            Console.WriteLine(regex.Replace(s, "*"));
            regex = new Regex(@"c$");
            Console.WriteLine(regex.Replace(s, "*"));

            //可以在创建正则表达式的时候指定正则表达式为多行匹配模式,匹配任意一行的开头和结尾
            regex = new Regex(@"^a",RegexOptions.Multiline);
            Console.WriteLine(regex.Replace(s, "*"));
            regex = new Regex(@"c$", RegexOptions.Multiline);
            Console.WriteLine(regex.Replace(s, "*"));

            Console.WriteLine("------------------------------------");

            //\A 必须出现字符串开头的位置,多行匹配也不会查询到其他行
            regex = new Regex(@"\Aa", RegexOptions.Multiline);
            Console.WriteLine(regex.Replace(s, "*"));


            //\Z 必须出现在字符串的结尾位置或者最后的\n之前,多行匹配也不会查询到其他的行
            s = "abc\nabc\n";
            regex = new Regex(@"c\Z", RegexOptions.Multiline);
            Console.WriteLine(regex.Replace(s, "*"));


            // \b  单词边界 表示这个位置不能出现其他的单词
            // abc cba acb ccc 
            // @"c\b"    ab* cba acb cc*

            // \B  非单词边界 表示这个位置必须出现其他的单词
            // abc cba acb ccc 
            // @"c\b"    abc *ba a*b **c
        }
    }
}

分组

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _08分组
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //分组构造,描述了正则表达式的子表达式,通常用于捕获输入字符串的字字符串

            string s = "aaaaa  bb cc a b c ab bc cccccc sssss";
            // 正则中使用() 将某一些子表达式括起来,将他们分为一组,组的编号从1开始
            //  在正则使用 \编号 引用分组匹配到的字符
            Regex regex = new Regex(@"(([a-z])\2{4})");
            regex = new Regex(@"(\w)\1");
            Console.WriteLine(regex.Replace(s,"*"));
        }
    }
}

正则查询

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _09正则查询
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // \u002f 等同于 /
            string s = "abc123abc234\u002f";
            Console.WriteLine(s);
            
            Regex regex = new Regex(@"[\d/]");

            // 正则对象的Match方法,用于从指定的字符串中查询满足条件的第一个匹配项
            Match m =  regex.Match(s);
            Console.WriteLine(m.Value);//匹配到的字符串  1

            Console.WriteLine(regex.Match(s).Value);

            //正则表达式的Matches方法,用于从指定的字符串中查询满足条件的所有的匹配项,的到的是一个Match集合
           MatchCollection ms=   regex.Matches(s);

            foreach (Match item in ms)
            {
                Console.WriteLine(item.Value);
            }

            Console.WriteLine(ms.Count);
        }
    }
}

正则查询练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _02正则查询练习
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请输入要查询的字符串或文件地址: ");
            string inputString = Console.ReadLine();
            // 判断文件是否存在
            if (File.Exists(inputString))
            {
                inputString = File.ReadAllText(inputString);
            }
        inputReg:
            Console.Write("请输入正则表达式: ");
            string inputReg = Console.ReadLine();

            // 根据输入的正则字符串,创建正则对象
            Regex reg = new Regex(inputReg);
            MatchCollection matchCollection = reg.Matches(inputString);

            // 先将所有查询到的字符位置和字符长度存储起来
            Dictionary<int, int> posAndLength = new Dictionary<int, int>();

            for (int i = 0; i < matchCollection.Count; i++)
            {
                Match m = matchCollection[i];
                // 在数组中存储当前字符的位置和长度
                posAndLength.Add(m.Index, m.Length);
            }
            // 循环输出字符串
            for (int i = 0; i < inputString.Length; i++)
            {
                // 如果字典中某个键和当前的索引一致
                if (posAndLength.ContainsKey(i))
                {
                    // 如果有这个键,循环子字符串串
                    for (int j = i; j < i + posAndLength[i]; j++)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write(inputString[j]);
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                    // 修改外层循环变量 i,防止字符串被重复输出
                    i = i + posAndLength[i] - 1;
                }
                else  // 没有这个键则直接输出即可
                {
                    Console.Write(inputString[i]);
                }
            }
            goto inputReg;

        }
    }
}

分组

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _03分组
{
    internal class Program
    {
        static void Main(string[] args)
        {

            string s = "abab 1212 aabb bbaa  cac dcd cdc 123 122  111 ccccccccc";

            // 在正则中可以使用() 对某些子表达式进行分组, 分组后的子表达式为一个整体,

            // 要匹配ab出现两次

            Regex regex = new Regex(@"ab{2}");//abb 因为{2}量词修饰的仅仅是前一个子表达式

            regex = new Regex(@"(ab){2}");//abab  使用()将ab括起来之后,ab这两个子表达式,就变成了一个整体,{2}修饰这个整体的字表达式
            regex = new Regex(@"(ab{2}){2}");//abbabb

            //还可以在正则中使用 \数字 来引用正则分组所捕获到的字符串,数字从1开始
            //如: 现在要匹配AA格式的字符串 
            regex = new Regex(@"(.)\1"); //匹配任意字符,后面要跟一个和前一个任意字符相同的字符

            //  如: 现在要匹配ABAB 格式的字符串

            regex = new Regex(@"(..)\1");

            可以有多个分组,从左小括号开始进行计数,分别使用\1\2\3..来引用
            regex = new Regex(@"(.)\1(.)\2\1\1\2\2");  //AABBAABB格式


            ()嵌套的时候,以()开始位置计算组编号
            第一组 ((.)\2{2}) 第二组 (.)
            regex = new Regex(@"((.)\2{2}){3}");//AAAAAAAAA
            
            Console.WriteLine(regex.Replace(s,"*"));

            //---------------------------------
            Console.WriteLine("--------------------------------");

            //命名分组: 直接使用使用小括号,进行分组可能会导致分组紊乱,不容易区分是哪个分组

            s = "1111-22-1111-22    1234-12-1231-12";
            //以下正则中给两个分组命名为year和month
            //使用\k<分组吗> 进行引用
           // 1111-11-1111-11
       regex = new Regex(@"(?<year>\d{4})-(?<month>\d{2})-\k<year>-\k<month>");

            Console.WriteLine("--------------------------");

            //非捕获型分组(分组的字符捕获是比较耗费性能的)
            //正则中()会自动进行匹配字符的捕获 后续可以使用\数字,引用这个分组捕获的内容
            //有时候我们仅仅是需要进行子表达式的分组,不需要捕获,可以在分组括号中的开始位置 ?: 表示这是一个非捕获型分组


            regex = new Regex(@"([a-z])([0-9])\1");// a1a c0c
            //非捕获型分组不会计入捕获的编号中
            regex = new Regex(@"(?:[a-z])([0-9])\1"); //a11 c00

            Console.WriteLine("----------------------");

            s = "abc \nABC \naBC \nabc \naBc";
            //(?i:子表达式) 该子表达式不区分大小写
            regex = new Regex(@"a(?i:bC)");// abc aBC  aAc
            //(?m:子表达式) 该子表达式支持多行匹配
            regex = new Regex(@"(?m:^a)");
            //(?mi:子表达式) 该子表达式支持多行匹配并且不区分大小写
            regex = new Regex(@"(?mi:^a)");
            Console.WriteLine(regex.Replace(s, "*"));


            Console.WriteLine("------------------------------");

            //正则表达式选项
            //可以在正则表达式创建的时候,通过参数2传递一些配置修改正则表达式的匹配模式

            s = "abc ABC Abc aBc";

            regex = new Regex(@"aBc",RegexOptions.IgnoreCase);//不区分大小写
            Console.WriteLine(regex.Replace(s, "*"));

            s = "abc\nABC\nAbc\naBc";

            regex = new Regex(@"^abc$",RegexOptions.Multiline);//多行匹配
            regex = new Regex(@"^abc$", RegexOptions.Multiline| RegexOptions.IgnoreCase);//多行匹配 并且忽略大小写
            Console.WriteLine(regex.Replace(s, "*"));

            s = "a b c";

            //开启后 正则中的非转义空格将被忽略(空格不表示空格 \空格 才表示空格) 并且启动以#开头的注释 
            // 以下正则表示匹配  空格c
            regex = new Regex(@"
                \    #这里有个空格
                c
           ", RegexOptions.IgnorePatternWhitespace);//不区分大小写
            Console.WriteLine(regex.Replace(s, "*"));

            //开启后,未命名的分组都将会变成非捕获型分组
            regex = new Regex(@"(\d\w)(?<1>\d{3}\1)",RegexOptions.ExplicitCapture);

            Console.WriteLine(regex.Replace(s, "*"));

            Console.WriteLine("------------------");
            s = "abc Abc aBC";
            可以使用(?-i:表达式) 让这个表达式区分大小写(在不区分大小写的模式下)
            regex = new Regex(@"(?-i:a)bc", RegexOptions.IgnoreCase);
            Console.WriteLine(regex.Replace(s, "*"));



        }
    }
}

零宽断言

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _04零宽断言
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //零宽断言:不占用宽度的匹配判断

            string s = "ab ac ad bac bab";

            // 表达式A(?=表达式B) 我要表达式A 但是后面必须满足表达式B,我要这个A
            //a(?=b) // 我要a 但是这个a后面必须有b

            Regex reg = new Regex(@"a(?=b)");
            Console.WriteLine(reg.Replace(s,"*"));

            // 表达式A(?!表达式B) 我要表达式A 但是后面必须不满足表达式B,我要这个A
            // a(?!b) // 我要a 但是这个a后面不能有b
            reg = new Regex(@"a(?!b)");
            Console.WriteLine(reg.Replace(s, "*"));


            //(?<=a)b  //我要b 但是前面必须是a
            reg = new Regex(@"(?<=a)b");
            Console.WriteLine(reg.Replace(s, "*"));

            //(?!=a)b  //我要b 但是前面不能是a
            reg = new Regex(@"(?<!a)b");
            Console.WriteLine(reg.Replace(s, "*"));



        }
    }
}

备用构造

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _05备用构造
{
    internal class Program
    {
        static void Main(string[] args)
        {

            //可以使用 () 和 | 进行多个表达式之间的或者关系表示

            // (aaa|bb|d1) 表示 aaa或者bb或者d1, 和[]的区别在于 []表示多个字符中的某个字符,这个表示多个表达式的某个表达式

            string s = "ab ac abc acd";
            Regex regex = new Regex(@"(ab|ac)");

            Console.WriteLine(regex.Replace(s, "*"));

            //正则中的三目运算
            //格式:(?(条件正则)条件成立的使用的正则|条件不成立使用的正则)

            s = "a1 b中 c中 d2";
            //如果是a或者b 则后面必须紧跟一个数字,如果不是则后面必须紧跟汉字
            regex = new Regex(@"(?([ab])[ab]\d|.[\u4e00-\u9fa5])");

            Console.WriteLine(regex.Replace(s, "*"));
        }
    }
}

替换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _06替换
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string s = "one two";

       
            // Replace 替换字符串也可以使用正则中分组捕获到的内容

            Regex reg =new Regex(@"\b(\w+)(\s)(\w+)\b");

            //使用$1 $2 $n,....第n个分组捕获的内容
            Console.WriteLine(reg.Replace(s,"第三组内容为$3,第二组内容为$2,第一组内容为$1"));

            Console.WriteLine(reg.Replace(s,"$1$1$1$2\t$2-$3$3"));


            reg = new Regex(@"\b(?<luoluo>\w+)(\s)(?<fanfan>\w+)\b");

            Console.WriteLine(reg.Replace(s, "${luoluo}-${fanfan}"));

            //$ 有特殊含义,因此必须使用$$ 才能表示$
            Console.WriteLine(reg.Replace(s, "$$${luoluo}-${fanfan}"));



            s = "123abc456";

            //$& 表示匹配到的所有的字符
            reg = new Regex(@"\d+");
            Console.WriteLine(reg.Replace(s,"($&)"));


            s = "123AAABBCC";



            //$` 表示匹配像前面所有的字符
            reg = new Regex(@"B+");
            Console.WriteLine(reg.Replace(s, "$`"));
            //$' 表示匹配像后面所有的字符
            reg = new Regex(@"B+");
            Console.WriteLine(reg.Replace(s, "$'"));

        }
    }
}

正则方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _07正则方法
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string s = "的诉讼法hdfi123123123dhihidfs";
            //1.IsMatch() 判断字符串是否符合正则表达式的验证规则
            //符合正则表达式返回true 不符合正则表达式返回false

            //类名.方法  (静态方法)
            Console.WriteLine(Regex.IsMatch(s, @"\d"));

            Regex reg = new Regex(@"\d");
            //实例对象.方法
            Console.WriteLine(reg.IsMatch(s));
            //从指定的索引位置开始查询
            Console.WriteLine(reg.IsMatch(s, 7));


            //2.Match()  从指定的正则中查询第一个满足条件的内容,返回一个Match对象,包含匹配的字符信息
            s = "现在的日期为:2022-22-16发斯蒂芬阿萨德刚辅导费";
            Match m = Regex.Match(s, @"(\d{4})-(\d{2})-(?<day>\d{2})");
            Console.WriteLine(m);
            Console.WriteLine(m.Value);
            Console.WriteLine(m.Index);//找到的位置
            Console.WriteLine(m.Groups[0]);//分组的第0个(所有的匹配项)
            Console.WriteLine(m.Groups[1]);//第一个分组
            Console.WriteLine(m.Groups[2]);//第二个分组
            Console.WriteLine(m.Groups[3]);//第三个分组
            Console.WriteLine(m.Groups["day"]);//分组day

            //3.Matches()   从指定的正则中查询所有满足条件的内容,返回一个Match集合 包含所有的匹配到的Match

            s = "fhysdi38rw143ehuierha";
            MatchCollection ms = Regex.Matches(s, @"\d");

            foreach (Match item in ms)
            {
                Console.WriteLine(item);
            }

            //4.Replace() 替换


            //5. Split  根据正则分割字符串
            string[] strs=   Regex.Split(s, @"\d");

            foreach (string item in strs)
            {
                Console.WriteLine(item);

            }


        }
    }
}

上期习题答案

封装一个类:Aircraft,拥有属性:牌子、型号、颜色、隶属公司、飞行速度、装载人数、飞机类型(大中小(400-200-100)由装载人数自动设置)、当前飞机装载的人数(随机生成)


下面是一个 `Aircraft` 类,其结构包含您所列出的属性,并包括逻辑来根据装载人数自动设置飞机类型。同时,默认构造器中为当前飞机载客量生成了一个随机值。

```csharp
using System;

public class Aircraft
{
    public string Brand { get; set; }
    public string Model { get; set; }
    public string Color { get; set; }
    public string CompanyOwned { get; set; }
    public double FlightSpeed { get; set; }

    private int _capacity;
    public int Capacity 
    {
        get => _capacity;
        set
        {
            _capacity = value;
            DetermineAircraftType();
        } 
    }

    public AircraftType Type { get; private set;}
    
    // 飞机类型枚举定义
    public enum AircraftType
    {
        Large,   // 大型,400 以上
        Medium,  // 中型,200 - 399
        Small     // 小型,100 - 199
    }

    private int _currentPassengers;
    
    // 假设飞机至少承载1个乘客也不可能超过其最大容量。
    public int CurrentPassengers 
    {
        get => _currentPassengers;
        private set => _currentPassengers = (value >= 1 && value <= Capacity) ? value : throw new ArgumentOutOfRangeException(nameof(value), "Current passenger count must be between 1 and capacity.");
                
    }

    // 构造方法,在创建对象的时候可以初始化一些基本信息。
    public Aircraft(string brand, string model, string color, string companyOwned, double flightSpeed)
    {
        Brand = brand;
        Model = model;
        Color = color;
        CompanyOwned = companyOwned;
        FlightSpeed = flightSpeed;

        // 初始化当前客户人数为随机值(暂定为5到最大容量之间)
       Random rnd = new Random();
       CurrentPassengers = rnd.Next(5, Capacity + 1);
        
       DetermineAircraftType();   
       
       if (CurrentPassengers > Capacity)
           CurrentPassengers = Capacity;
          
           
      }

      // 根据容量确定飞行器类型。
      private void DetermineAircraftType()
      {
          if (_capacity >= 400)
          {
              Type = AircraftType.Large;
          }
          else if (_capacity >= 200)
          {
              Type = AircraftType.Medium;
          }
          else if (_capacity >= 100)
          {
              Type = AircraftType.Small;
          }
      }
}

在上面代码中:

  • 我添加了一个私有字段 _capacity 和相应的公共属性 Capacity,每当装载人数被设置时就会根据这个值来自动更新飞机类型。
  • 此外还有一个枚举 AircraftType, 表示不同大小的飞机。
  • DetermineAircraftType() 方法是用来根据 Capacity 属性设置 Type 属性(飞机类别)的私有方法。
  • 在默认构造函数内部,它将利用随机数填充 _currentPassenger 属性以模拟当前登记的旅客数量。

请注意,对于属性,我使用 getset
访问器以控制如何获取和设置数据。例如,在尝试给出超出航空器承载范围之外旅客数量时抛出异常。

此类设计考虑到一定的简洁和强壮性,但不涉及真实世界中飞行器管理系统的复杂性。在生产环境中,你可能需要更多详细信息、验证和商务规则。

本期习题

  1. 验证一个车牌是否符合规范
  2. 接收用户输入一个邮箱, 正则验证邮箱是否正确
  3. 接收用户输入一个 xxxx-xx-xx格式的字符,判断是否为有效的日期(不考虑2月和平闰年)

拓展博客: https://blog.csdn.net/fd2025/article/details/125326832

  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值