zl程序教程

您现在的位置是:首页 >  其他

当前栏目

C# 使用正则表达式

2023-02-18 16:46:26 时间

校验数字的表达式: 常用的针对数字的匹配符号。

Regex(@"^[0-9]*$");                       // 匹配0-9数字
Regex(@"^\d{n}$");                        // 匹配出现过n次的数字
Regex(@"^\d{n,}$");                       // 匹配至少出现过n次的数字
Regex(@"^\d{m,n}$");                      // 匹配最小出现过m次最大n次的数字
Regex(@"^(0|[1-9][0-9]*)$");              // 匹配零和非零开头的数字
Regex(@"^([1-9][0-9]*)+(.[0-9]{1,2})?$"); // 匹配非零开头的最多带两位小数的数字
Regex(@"^(\-)?\d+(\.\d{1,2})?$");         // 匹配带1-2位小数的正数或负数
Regex(@"^(\-|\+)?\d+(\.\d+)?$");          // 匹配正数、负数、和小数
Regex(@"^[0-9]+(.[0-9]{2})?$");           // 匹配有两位小数的正实数
Regex(@"^[0-9]+(.[0-9]{1,3})?$");         // 匹配有1~3位小数的正实数

Regex(@"^[1-9]\d*$");                     // 匹配非零的正整数                 
Regex(@"^([1-9][0-9]*){1,3}$");           // 同上
Regex(@"^\+?[1-9][0-9]*$");               // 同上

Regex(@"^\-[1-9][]0-9"*$);                // 匹配非零负整数
Regex(@"^-[1-9]\d*$");

Regex(@"^\d+$");                          // 匹配非负整数
Regex(@"^[1-9]\d*|0$");
Regex(@"^-[1-9]\d*|0$");                  // 匹配非正整数
Regex(@"^((-\d+)|(0+))$");

Regex(@"^(-?\d+)(\.\d+)?$");              // 匹配浮点数
Regex(@"^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$");

Regex(@"^\d+(\.\d+)?$");                  // 匹配非负浮点数
Regex(@"^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$");

Regex(@"^((-\d+(\.\d+)?)|(0+(\.0+)?))$"); // 匹配非正浮点数
Regex(@"^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$");

Regex(@"^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$")     // 匹配正浮点数
Regex(@"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$");

Regex(@"^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$"); // 匹配负浮点数
Regex(@"^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$");

校验字符的表达式

Regex(@"^[\u4e00-\u9fa5]{0,}$");          // 匹配汉字
Regex(@"^[A-Za-z0-9]+$");                 // 匹配英文和数字
Regex(@"^[A-Za-z0-9]{4,40}$");            // 匹配应为和数字,最小4位最大40位
Regex(@"^.{3,20}$");                      // 匹配长度为3-20的所有字符

Regex(@"^[A-Za-z]+$");                    // 匹配由26个英文字母组成的字符串
Regex(@"^[A-Z]+$");                       // 匹配由26个大写英文字母组成的字符串
Regex(@"^[a-z]+$");                       // 匹配由26个小写英文字母组成的字符串
Regex(@"^[A-Za-z0-9]+$");                 // 匹配由数字和26个英文字母组成的字符串
Regex(@"^\w+$ 或 ^\w{3,20}$");            // 匹配由数字、26个英文字母或者下划线组成的字符串

Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");     // 匹配中文、英文、数字包括下划线
Regex(@"^[\u4E00-\u9FA5A-Za-z0-9]+$");      // 匹配中文、英文、数字但不包括下划线等符号
Regex(@"^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$"); // 同上,不过这里可以限制长度

Regex(@"[^%&’,;=?$\x22]+");                 // 可以输入含有^%&’,;=?$\"等字符
Regex(@"[^~\x22]+");                        // 禁止输入含有~的字符

特殊需求表达式

Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");   // 验证email地址

Regex(@"[a-zA-z]+://[^\s]*");                              // 验证URL网址
Regex(@"^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$");
Regex(@"^([a-zA-Z]+://)?([\w-\.]+)(\.[a-zA-Z0-9]+)(:\d{0,5})?/?([\w-/]*)\.?([a-zA-Z]*)\??(([\w-]*=[\w%]*&?)*)$");

Regex(@"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$");  // 验证手机号码

Regex(@"^($$\d{3,4}-)|\d{3.4}-)?\d{7,8}$");               // 验证电话号码
Regex(@"\d{3}-\d{8}|\d{4}-\d{7}");                        // 验证国内电话号码

Regex(@"^\d{15}|\d{18}$");                                                 // 身份证号(15位、18位数字)
Regex(@"^([0-9]){7,18}(x|X)?$ 或 ^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$");  // 短身份证号码(数字、字母x结尾)

//帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线)
Regex(@"^[a-zA-Z][a-zA-Z0-9_]{4,15}$");

//密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线)
Regex(@"^[a-zA-Z]\w{5,17}$");

//强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间)
Regex(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$");

//日期格式
Regex(@"^\d{4}-\d{1,2}-\d{1,2}");
//一年的12个月(01~09和1~12)
Regex(@"^(0?[1-9]|1[0-2])$");
//一个月的31天(01~09和1~31)
Regex(@"^((0?[1-9])|((1|2)[0-9])|30|31)$");


//钱的输入格式:
//有四种钱的表示形式我们可以接受:”10000.00″ 和 “10,000.00”, 和没有 “分” 的 “10000” 和 “10,000”
Regex(@"^[1-9][0-9]*$");

//这表示任意一个不以0开头的数字,但是,这也意味着一个字符”0″不通过,所以我们采用下面的形式
Regex(@"^(0|[1-9][0-9]*)$");

//一个0或者一个不以0开头的数字.我们还可以允许开头有一个负号
Regex(@"^(0|-?[1-9][0-9]*)$");

//这表示一个0或者一个可能为负的开头不为0的数字.让用户以0开头好了.把负号的也去掉,因为钱总不能是负的吧.下面我们要加的是说明可能的小数部分
Regex(@"^[0-9]+(.[0-9]+)?$");

//必须说明的是,小数点后面至少应该有1位数,所以”10.”是不通过的,但是 “10” 和 “10.2” 是通过的
Regex(@"^[0-9]+(.[0-9]{2})?$");
//这样我们规定小数点后面必须有两位,如果你认为太苛刻了,可以这样
Regex(@"^[0-9]+(.[0-9]{1,2})?$");
//这样就允许用户只写一位小数。下面我们该考虑数字中的逗号了,我们可以这样
Regex(@"^[0-9]{1,3}(,[0-9]{3})*(.[0-9]{1,2})?$");
//1到3个数字,后面跟着任意个 逗号+3个数字,逗号成为可选,而不是必须
Regex(@"^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$");

//xml文件
Regex(@"^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\.[x|X][m|M][l|L]$");
//中文字符的正则表达式
Regex(@"[\u4e00-\u9fa5]");
//双字节字符
Regex(@"[^\x00-\xff] (包括汉字在内,可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1))");
//空白行的正则表达式,可用来删除空白行
Regex(@"\n\s*\r");
//HTML标记的正则表达式
Regex(@"<(\S*?)[^>]*>.*?</\1>|<.*? />");// (网上流传的版本太糟糕,上面这个也仅仅能部分,对于复杂的嵌套标记依旧无能为力)
//首尾空白字符的正则表达式
Regex(@"^\s*|\s*$或(^\s*)|(\s*$)");// (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式)
//腾讯QQ号
Regex(@"[1-9][0-9]{4,}"); //(腾讯QQ号从10000开始)
//中国邮政编码
Regex(@"[1-9]\d{5}(?!\d)");// (中国邮政编码为6位数字)
//IP地址
Regex(@"\d+\.\d+\.\d+\.\d+");// (提取IP地址时有用)
Regex(@"((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))");

使用正则匹配: C#中字符串常量以@开头,这样优点是转义序列不被处理,按“原样”输出

matches = 在指定的输入字符串中搜索正则表达式的所有匹配项。 match = 在指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式的第一个匹配项。

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 正则匹配的基本使用1

            string str = "Address=192.168.1.1;Name=lyshark;Host=9999";

            Regex reg = new Regex("Name=(.+);");  // 设置匹配条件
            Match match = reg.Match(str);         // 匹配

            string value = match.Groups[0].Value; // 获取到匹配结果
            Console.WriteLine("匹配到数据: " + value);

            // 正则匹配的基本使用2
            string input = "1986 1997 2005 2009 2019 1951 1999 1950 1905 2003";
            string pattern = @"(?<=19)\d{2}\b";

            foreach(Match each in Regex.Matches(input,pattern))
            {
                Console.WriteLine("匹配到时间: " + each.Value);
            }

            Console.ReadKey();
        }
    }
}

正则替换字符: replace 在指定的输入字符串内,使用指定的替换字符串替换与某个正则表达式模式匹配的所有字符串。

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 正则替换掉指定单词
            string line = "Address=192.168.1.10;  Name=lyshark;";
            Regex reg_line = new Regex("Name=(.+);");
            string modified = reg_line.Replace(line, "Name=admin;");
            Console.WriteLine("修改后的结果:  " + modified);

            // 正则替换掉多余空格
            string input = "Hello    World     ";
            string pattern = "\\s+";
            string replacement = " ";

            Regex reg = new Regex(pattern);
            string result = reg.Replace(input, replacement);

            Console.WriteLine("替换前:{0} 替换后:{1}", input, result);

            Console.ReadKey();
        }
    }
}

判断字符串状态: IsMatch 指示 Regex 构造函数中指定的正则表达式在指定的输入字符串中是否找到了匹配项。

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string RegexStr = string.Empty;
            // 匹配字符串的开始和结束是否为0-9的数字[定位字符]
            RegexStr = "^[0-9]+$";
            Console.WriteLine("判断是否为数字: {0}", Regex.IsMatch("1234", RegexStr));

            // 匹配字符串中间是否包含数字(任意位子只要有一个数字即可)
            RegexStr = @"\d+";
            Console.WriteLine("判断是否包含数字: {0}", Regex.IsMatch("你好123", RegexStr));

            // 匹配字符串开头结尾,忽略大小写
            RegexStr = @"Hello[\w\W]*";
            Console.WriteLine("匹配是否以Hello开头: {0}", Regex.IsMatch("Hello Lyshark", RegexStr, RegexOptions.IgnoreCase));

            RegexStr = @"[\w\W*]Hello";
            Console.WriteLine("匹配是否已Hello结尾: {0}", Regex.IsMatch("Hello Lyshark", RegexStr, RegexOptions.IgnoreCase));

            Console.ReadKey();
        }
    }
}

正则分组匹配:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string RegexStr = string.Empty;

            // 匹配所行记录数
            string TaobaoLink = "<a href=\"http://www.taobao.com\" title=\"淘宝网\" target=\"_blank\">淘宝</a>";
            RegexStr = @"<a[^>]+href=""(\S+)""[^>]+title=""([\s\S]+?)""[^>]+>(\S+)</a>";
            
            Match mat = Regex.Match(TaobaoLink, RegexStr);
            for (int i = 0; i < mat.Groups.Count; i++)
            {
                Console.WriteLine(mat.Groups[i].Value);
            }

            // 分组匹配
            string Resume = "姓名:lyshark|性别:男|出生日期:1991-12-12|手机:18264855695";
            RegexStr = @"姓名:(?<name>[\S]+)\|性别:(?<sex>[\S]{1})\|出生日期:(?<Birth>[\S]{10})\|手机:(?<phone>[\d]{11})";
            Match match = Regex.Match(Resume, RegexStr);
            Console.WriteLine("姓名:{0} 手机号: {1}", match.Groups["name"].ToString(),match.Groups["phone"].ToString());

            Console.ReadKey();
        }
    }
}

正则拆分字符串:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string SplitInputStr = "1xxxxx.2ooooo.3eeee.4kkkkkk.";
            string RegexStr = string.Empty;

            RegexStr = @"(\d)";
            Regex split_exp = new Regex(RegexStr);
            string[] str = split_exp.Split(SplitInputStr);

            foreach (string each in str)
                Console.WriteLine(each);

            Console.ReadKey();
        }
    }
}

解析HTML标签:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 获得href中的值
            string RegexStr = string.Empty;

            string LinkA = "<a href=\"http://www.baidu.com\" target=\"_blank\">百度</a>";
            RegexStr = @"href=""[\S]+""";
            Match match = Regex.Match(LinkA, RegexStr);
            Console.WriteLine("获得href中的值: {0}", match.Value);

            // 匹配标签
            string LinkB = "<h1>hellolyshark</h1>";
            RegexStr = @"<h[^23456]>[\S]+</h[1]>";
            Console.WriteLine("h1值: {0}", Regex.Match(LinkB, RegexStr, RegexOptions.IgnoreCase).Value);



            RegexStr = @"ab\w+|ij\w{1,}";   //匹配ab和字母 或 ij和字母
            Console.WriteLine("{0}。多选结构:{1}", "abcd", Regex.Match("abcd", RegexStr).Value);
            Console.WriteLine("{0}。多选结构:{1}", "efgh", Regex.Match("efgh", RegexStr).Value);
            Console.WriteLine("{0}。多选结构:{1}", "ijk", Regex.Match("ijk", RegexStr).Value);



            RegexStr = @"张三?丰";    //?匹配前面的子表达式零次或一次。
            Console.WriteLine("{0}。可选项元素:{1}", "张三丰", Regex.Match("张三丰", RegexStr).Value);
            Console.WriteLine("{0}。可选项元素:{1}", "张丰", Regex.Match("张丰", RegexStr).Value);
            Console.WriteLine("{0}。可选项元素:{1}", "张飞", Regex.Match("张飞", RegexStr).Value);

            //匹配特殊字符
            RegexStr = @"Asp\.net";    //匹配Asp.net字符,因为.是元字符他会匹配除换行符以外的任意字符。
            Console.WriteLine("{0}。匹配Asp.net字符:{1}", "Java Asp.net SQLServer", Regex.Match("Java Asp.net", RegexStr).Value);
            Console.WriteLine("{0}。匹配Asp.net字符:{1}", "C# Java", Regex.Match("C# Java", RegexStr).Value);


            Console.ReadKey();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string PageInfo = @"<hteml>
                        <div id=""div1"">
                            <a href=""http://www.baidu.con"" target=""_blank"">百度</a>
                            <a href=""http://www.taobao.con"" target=""_blank"">淘宝</a>
                            <a href=""http://www.cnblogs.com"" target=""_blank"">博客园</a>
                            <a href=""http://www.google.con"" target=""_blank"">google</a>
                        </div>
                        <div id=""div2"">
                            <a href=""/zufang/"">整租</a>
                            <a href=""/hezu/"">合租</a>
                            <a href=""/qiuzu/"">求租</a>
                            <a href=""/ershoufang/"">二手房</a>
                            <a href=""/shangpucz/"">商铺出租</a>
                        </div>
                    </hteml>";
            string RegexStr = string.Empty;
            RegexStr = @"<a[^>]+href=""(?<href>[\S]+?)""[^>]*>(?<text>[\S]+?)</a>";
            MatchCollection mc = Regex.Matches(PageInfo, RegexStr);

            foreach (Match item in mc)
            {
                Console.WriteLine("href:{0}--->text:{1}", item.Groups["href"].ToString(), item.Groups["text"].ToString());
            }

            Console.ReadKey();
        }
    }
}