c#高级-正则表达式

正则表达式是由普通字符和元字符(特殊符号)组成的文字形式

应用场景

1.用于验证输入的邮箱是否合法。

2.用于验证输入的电话号码是否合法。

3.用于验证输入的身份证号码是否合法。等等

正则表达式常用的限定符总结:

几种常用的正则简写表达式总结:

如下图所示:

正则表达式的几个案例演示:

代码如下所示:

cs 复制代码
namespace Program_正则表达式练习
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //匹配IP地址,分割

            //while (true)
            //{
            //    Console.WriteLine("请输入一个IP地址");
            //    string input = Console.ReadLine();
            //    bool b = Regex.IsMatch(input, @"(\d{1,3}\.){3}\d{1,3}");
            //    Console.WriteLine(b);
            //    Console.ReadKey();

            //    Console.WriteLine("判断是否是合法的日期格式:");
            //    string input1 = Console.ReadLine();
            //    bool b1 = Regex.IsMatch(input1, "[0-8]{4}-[0][1-9]|[1][0-2]-[]");
            //}


            //1、从文件路径中提取出文件名(包含后缀) @"^.+\(.+)$"。比如从c:\windows\testb.txt中提取出testb.txt这个文件名出来。项目中用Path.GetFileName更好
            string path = @"C:\Users\26352\Desktop\text.txt";
            string name = Path.GetFileName(path);
            Console.WriteLine(name);

            //2.2、从"June         26       ,        1951    "中提取出月份June、26、1951提取出来。
            string input = "June   26   ,1951   ";
            MatchCollection mt = Regex.Matches(input, @"\w+");


            foreach (Match m in mt)
            {
                Console.WriteLine(m.Value);
            }

            //3、从Email中提取出用户名和域名,比如从test@163.com中提取出test和163.com。
            string input1 = "test@163.com";
            Match mt1 = Regex.Match(input1,@"(.+)@(.+)");
            if (mt1.Success)
            {
                Console.WriteLine(mt1.Groups[1].Value);
                Console.WriteLine(mt1.Groups[2].Value);
            }

            //4.
            string str = "192.168.10.5[port=21,type=ftp]";
            Match m3 = Regex.Match(str, @"(.+)\[port=(.+),type=(.+)\]");
            if(m3.Success)
            {
                Console.WriteLine(m3.Groups[1].Value);
                Console.WriteLine(m3.Groups[2].Value);
                Console.WriteLine(m3.Groups[3].Value);
            }
            Console.ReadKey();
        }
    }
}
相关推荐
czhc11400756631 小时前
Linux108 shell:.bashrc 正则表达式:. * .* ^ $ ^$ [ ] [^] ^[] ^[^ ] \< \>
linux·正则表达式
数据知道2 小时前
Go基础:正则表达式 regexp 库详解
开发语言·mysql·golang·正则表达式·go语言
利刃大大12 小时前
【高并发服务器】三、正则表达式的使用
服务器·c++·正则表达式·项目
尘觉4 天前
正则表达式入门与进阶(优化版)
正则表达式
AI悦创|编程1v15 天前
00-1-正则表达式学习心得:从入门到上瘾,再到克制
数据仓库·正则表达式·数据挖掘·ai悦创编程一对一教学·python一对一辅导·python一对一教学
带土15 天前
PHP 中的正则表达式
正则表达式·php
taller_20006 天前
VBA之正则表达式(45)-- 拆分材料和规格
正则表达式·正则·数据清洗·提取数据·材料规格
光明磊6 天前
正则表达式Regex
正则表达式
AI悦创|编程1v16 天前
01-元字符:如何巧妙记忆正则表达式的基本元件?
正则表达式·ai悦创编程一对一教学·python一对一辅导·python一对一教学
課代表7 天前
Acrobat DC 文本域表单验证中的 js 使用
javascript·正则表达式·表单验证·数据完整性·字段验证·事件对象·自定义验证