C# 正则表达式大全(代码篇)

您所在的位置:网站首页 正则表达式代码示例怎么写 C# 正则表达式大全(代码篇)

C# 正则表达式大全(代码篇)

2024-07-01 15:00| 来源: 网络整理| 查看: 265

目录

C# 正则表达式大全(理论篇)

C# 正则表达式大全(代码篇)

正则表达式的本质是使用一系列特殊字符模式,来表示某一类字符串。正则表达式无疑是处理文本最有力的工具,而.NET提供的Regex类实现了验证正则表达式的方法。

一、命名空间

System.Text.RegularExpressions命名空间提供可在 .NET 中运行的任何平台或语言中使用的正则表达式功能。 除了此命名空间中包含的类型外,RegexStringValidator 类还允许您确定特定字符串是否与某个正则表达式模式相符。

1.1 类 Capture:表示来自单个成功子表达式捕获的结果。 CaptureCollection:表示单个捕获组执行的捕获集。 该集合是不可变的(只读),没有公共构造函数。 Group:表示来自单个捕获组的结果,由Capture继承而来。 GroupCollection:返回一次匹配中捕获的组的集。 该集合是不可变的(只读),没有公共构造函数。 Match:表示单个正则表达式匹配的结果,由Group继承而来。 MatchCollection:表示通过以迭代方式将正则表达式模式应用于输入字符串所找到的成功匹配的集合。 该集合是不可变的(只读),没有公共构造函数。 Matches(String) 方法将返回 MatchCollection 对象。 Regex:表示不可变的正则表达式。 RegexCompilationInfo:提供有关使用正则表达式将正则表达式编译为独立程序集的信息。 RegexMatchTimeoutException:正则表达式模式匹配方法的执行时间超出其超时时间间隔时引发的异常。 RegexParseException:正则表达式中的分析错误导致的异常,Error 和 Offset 属性中包含了详细信息。 RegexRunner:RegexRunner 类是编译正则表达式的基类。 RegexRunnerFactory:为编译过的正则表达式创建 RegexRunner 类。 1.2 枚举 RegexOptions:提供用于设置正则表达式选项的枚举值。 RegexParseError:指定当正则表达式包含分析错误时引发 RegexParseException 的详细基本原因。 1.3 委托 MatchEvaluator:表示此方法,此方法于每次在 Replace 方法操作期间找到单一正则表达式匹配时调用。 1.4 Regex类静态方法 Escape: 对字符串中的regex中的转义符进行转义; IsMatch: 如果表达式在字符串中匹配,该方法返回一个布尔值; Match: 返回Match的实例; Matches: 返回一系列的Match的方法; Replace: 用替换字符串替换匹配的表达式; Split: 返回一系列由表达式决定的字符串; Unescape:不对字符串中的转义字符转义。 二、Regex类 2.1 构造函数 Regex() //初始化 Regex 类的新实例。 Regex(SerializationInfo, StreamingContext) //使用序列化数据初始化 Regex 类的新实例。 Regex(String) //为指定的正则表达式初始化 Regex 类的新实例。 Regex(String, RegexOptions) //使用修改模式的选项为指定的正则表达式初始化 Regex 类的新实例。 Regex(String, RegexOptions, TimeSpan) //使用修改模式的选项和指定在超时前多久模式匹配方法应进行匹配尝试的值为指定正则表达式初始化 Regex 类的新实例。 2.2 字段 capnames //由 CompileToAssembly 方法生成的 Regex 对象使用。 caps //由 CompileToAssembly 方法生成的 Regex 对象使用。 capsize //由 CompileToAssembly 方法生成的 Regex 对象使用。 capslist //由 CompileToAssembly 方法生成的 Regex 对象使用。 factory //由 CompileToAssembly 方法生成的 Regex 对象使用。 InfiniteMatchTimeout //指定模式匹配操作不应超时。 internalMatchTimeout //操作超时之前在一个模式匹配操作中可以经过的最长时间。 pattern //由 CompileToAssembly 方法生成的 Regex 对象使用。 roptions //由 CompileToAssembly 方法生成的 Regex 对象使用。 2.3 属性 CacheSize //获取或设置已编译的正则表达式的当前静态缓存中的最大项数。 CapNames //获取或设置将命名捕获组映射到其索引值的字典。 Caps //获取或设置将编号捕获组映射到其索引值的字典。 MatchTimeout //获取当前实例的超时间隔。 Options //获取传递给 Regex 构造函数的选项。 RightToLeft //获取一个值,该值指示正则表达式是否从右向左进行搜索。 2.4 方法 CompileToAssembly(RegexCompilationInfo[], AssemblyName) //将一个或多个指定的 Regex 对象编译为命名程序集。 CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) //将一个或多个指定的 Regex 对象编译为具有指定特性的命名程序集。 CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) //将一个或多个指定的 Regex 对象和一个指定的资源文件编译为具有指定特性的命名程序集。 Equals(Object) //确定指定对象是否等于当前对象。(继承自 Object) Escape(String) //通过替换为转义码来转义最小的字符集(\、*、+、?、|、{、[、(、)、^、$、.、# 和空白)。 这将指示正则表达式引擎按原义解释这些字符而不是解释为元字符。 GetGroupNames() //返回正则表达式的捕获组名数组。 GetGroupNumbers() //返回与数组中的组名相对应的捕获组号的数组。 GetHashCode() //作为默认哈希函数。(继承自 Object) GetType() //获取当前实例的 Type。(继承自 Object) GroupNameFromNumber(Int32) //获取与指定组号相对应的组名。 GroupNumberFromName(String) //返回与指定组名相对应的组号。 InitializeReferences() //由 CompileToAssembly 方法生成的 Regex 对象使用。 IsMatch(String) //指示 Regex 构造函数中指定的正则表达式在指定的输入字符串中是否找到了匹配项。 IsMatch(String, Int32) //指示 Regex 构造函数中指定的正则表达式在指定的输入字符串中,从该字符串中的指定起始位置开始是否找到了匹配项。 IsMatch(String, String) //指示所指定的正则表达式在指定的输入字符串中是否找到了匹配项。 IsMatch(String, String, RegexOptions) //指示所指定的正则表达式是否使用指定的匹配选项在指定的输入字符串中找到了匹配项。 IsMatch(String, String, RegexOptions, TimeSpan) //指示所指定的正则表达式是否使用指定的匹配选项和超时间隔在指定的输入字符串中找到了匹配项。 Match(String) //在指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式的第一个匹配项。 Match(String, Int32) //从输入字符串中的指定起始位置开始,在该字符串中搜索正则表达式的第一个匹配项。 Match(String, Int32, Int32) //从指定的起始位置开始,在输入字符串中搜索正则表达式的第一个匹配项,并且仅搜索指定数量的字符。 Match(String, String) //在指定的输入字符串中搜索指定的正则表达式的第一个匹配项。 Match(String, String, RegexOptions) //使用指定的匹配选项在输入字符串中搜索指定的正则表达式的第一个匹配项。 Match(String, String, RegexOptions, TimeSpan) //使用指定的匹配选项和超时间隔在输入字符串中搜索指定的正则表达式的第一个匹配项。 Matches(String) //在指定的输入字符串中搜索正则表达式的所有匹配项。 Matches(String, Int32) //从字符串中的指定起始位置开始,在指定的输入字符串中搜索正则表达式的所有匹配项。 Matches(String, String) //在指定的输入字符串中搜索指定的正则表达式的所有匹配项。 Matches(String, String, RegexOptions) //使用指定的匹配选项在指定的输入字符串中搜索指定的正则表达式的所有匹配项。 Matches(String, String, RegexOptions, TimeSpan) //使用指定的匹配选项和超时间隔在指定的输入字符串中搜索指定的正则表达式的所有匹配项。 MemberwiseClone() //创建当前 Object 的浅表副本。(继承自 Object) Replace(String, MatchEvaluator) //在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有字符串。 Replace(String, MatchEvaluator, Int32) //在指定的输入字符串内,使用 MatchEvaluator 委托返回的字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。 Replace(String, MatchEvaluator, Int32, Int32) //在指定的输入子字符串内,使用 MatchEvaluator 委托返回的字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。 Replace(String, String) //在指定的输入字符串内,使用指定的替换字符串替换与某个正则表达式模式匹配的所有的字符串。 Replace(String, String, Int32) //在指定输入字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。 Replace(String, String, Int32, Int32) //在指定输入子字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。 Replace(String, String, MatchEvaluator) //在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有字符串。 Replace(String, String, MatchEvaluator, RegexOptions) //在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有字符串。 指定的选项将修改匹配操作。 Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan) //在指定的输入字符串中,使用由 MatchEvaluator 委托返回的字符串替换与指定的正则表达式匹配的所有子字符串。 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。 Replace(String, String, String) //在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。 Replace(String, String, String, RegexOptions) //在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。 指定的选项将修改匹配操作。 Replace(String, String, String, RegexOptions, TimeSpan) //在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。 Split(String) //在由 Regex 构造函数指定的正则表达式模式所定义的位置,将输入字符串拆分为子字符串数组。 Split(String, Int32) //在由 Regex 构造函数中指定的正则表达式定义的位置,将输入字符串拆分为子字符串数组指定的最大次数。 Split(String, Int32, Int32) //在由 Regex 构造函数中指定的正则表达式定义的位置,将输入字符串拆分为子字符串数组指定的最大次数。 从输入字符串的指定字符位置开始搜索正则表达式模式。 Split(String, String) //在由正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。 Split(String, String, RegexOptions) //在由指定正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。 指定的选项将修改匹配操作。 Split(String, String, RegexOptions, TimeSpan) //在由指定正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。 ToString() //返回传入 Regex 构造函数的正则表达式模式。 Unescape(String) //转换输入字符串中的任何转义字符。 UseOptionC() //由 CompileToAssembly 方法生成的 Regex 对象使用。 UseOptionR() //由 CompileToAssembly 方法生成的 Regex 对象使用。 ValidateMatchTimeout(TimeSpan) //检查超时间隔是否在可接受的范围内。 三、Regex类常用静态方法

Regex类有很多静态和非静态方法,下面介绍一下常用的几个静态方法。

3.1 静态Match方法

在输入字符串中搜索匹配正则表达式模式的子字符串,并将返回第一个匹配项。

静态的Match方法有3个重载,分别是

public static Match Match (string input, string pattern); //输入、模式 public static Match Match (string input, string pattern, RegexOptions options); //指定匹配选项,枚举的“按位或”组合 public static Match Match (string input, string pattern, RegexOptions options, TimeSpan matchTimeout); //指定超时间隔

RegexOptions枚举的有效值是:

Complied 表示编译此模式 CultureInvariant 表示不考虑文化背景 ECMAScript 表示符合ECMAScript,这个值只能和IgnoreCase、Multiline、Complied连用 ExplicitCapture 表示只保存显式命名的组 IgnoreCase 表示不区分输入的大小写 IgnorePatternWhitespace 表示去掉模式中的非转义空白,并启用由#标记的注释 Multiline 表示多行模式,改变元字符^和$的含义,它们可以匹配行的开头和结尾 None 表示无设置,此枚举项没有意义 RightToLeft 表示从右向左扫描、匹配,这时,静态的Match方法返回从右向左的第一个匹配 Singleline 表示单行模式,改变元字符.的意义,它可以匹配换行符

注意:Multiline在没有ECMAScript的情况下,可以和Singleline连用。Singleline和Multiline不互斥,但是和ECMAScript互斥。

示例:

//匹配以字母 "a" 开头的单词 string pattern = @"\ba\w*\b"; string input = "An extraordinary day dawns with each new day."; Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase); //忽略大小写 if (m.Success) Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index); //匹配的值和位置 // The example displays the following output: // Found 'An' at position 0. 3.2 静态Matches方法

这个方法的重载形式同静态的Match方法,返回一个MatchCollection, 如果未找到匹配项,则此方法将返回一个空集合对象。重载方法如下:

public static MatchCollection Matches (string input, string pattern); public static MatchCollection Matches (string input, string pattern, RegexOptions options); public static MatchCollection Matches (string input, string pattern, RegexOptions options, TimeSpan matchTimeout);

示例:

//标识句子中以 "es" 结尾的任何单词 string pattern = @"\b\w+es\b"; string sentence = "Who writes these notes?"; foreach (Match match in Regex.Matches(sentence, pattern)) Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index); // The example displays the following output: // Found 'writes' at position 4 // Found 'notes' at position 17 3.3 静态IsMatch方法

指示正则表达式在输入字符串中是否找到匹配项。重载方法如下:

public static bool IsMatch (string input, string pattern); public static bool IsMatch (string input, string pattern, RegexOptions options); public static bool IsMatch (string input, string pattern, RegexOptions options, TimeSpan matchTimeout);

可以理解为:IsMatch方法,返回Matches方法返回的集合是否为空。

示例:

string[] partNumbers = { "1298-673-4192", "A08Z-931-468A", "_A90-123-129X", "12345-KKA-1230", "0919-2893-1256" }; string pattern = @"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$"; foreach (string partNumber in partNumbers) Console.WriteLine("{0} {1} a valid part number.", partNumber, Regex.IsMatch(partNumber, pattern) ? "is" : "is not"); // The example displays the following output: // 1298-673-4192 is a valid part number. // A08Z-931-468A is a valid part number. // _A90-123-129X is not a valid part number. // 12345-KKA-1230 is not a valid part number. // 0919-2893-1256 is not a valid part number. 四、Regex类的实例 4.1 字符串替换 //例如我想把如下格式记录中的`NAME`值修改为WANG string line = "ADDR=1234;NAME=ZHANG;PHONE=6789"; Regex reg = new Regex("NAME=(.+);"); string modified = reg.Replace(line, "NAME=WANG;"); //修改后的字符串为 ADDR=1234;NAME=WANG;PHONE=6789 4.2 字符串匹配 string line = "ADDR=1234;NAME=ZHANG;PHONE=6789"; Regex reg = new Regex("NAME=(.+);"); //例如我想提取`line`中的`NAME`值 Match match = reg.Match(line); string value = match.Groups[1].Value; Console.WriteLine("value的值为:{0}", value);

4.3 Match实例 //文本中含有"speed=30.3mph",需要提取该速度值,但是速度的单位可能是公制也可能是英制,mph,km/h,m/s都有可能;另外前后可能有空格。 string line = "lane=1;speed=30.3mph;acceleration=2.5mph/s"; Regex reg = new Regex(@"speed\s*=\s*([\d\.]+)\s*(mph|km/h|m/s)*"); Match match = reg.Match(line); //那么在返回的结果中match.Groups[1].Value将含有数值,而match.Groups[2].Value将含有单位。 var 值 = match.Groups[1].Value; //匹配的组 var 单位 = match.Groups[2].Value; Console.WriteLine("speed的值为:{0} speed的单位是:{1}", 值,单位);

4.4 解码gps的GPRMC字符串 //就可以获得经度、纬度值,而以前需要几十行代码。 Regex reg = new Regex(@"^\$GPRMC,[\d\.]*,[A|V],(-?[0-9]*\.?[0-9]+),([NS]*),(-?[0-9]*\.?[0-9]+),([EW]*),.*"); 4.5 提取[]的值 string pattern = @"(?is)(?.*?|");// (网上流传的版本太糟糕,上面这个也仅仅能部分,对于复杂的嵌套标记依旧无能为力) //首尾空白字符的正则表达式 Regex reg = new Regex(@"^\s*|\s*$或(^\s*)|(\s*$)");// (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式) //腾讯QQ号 Regex reg = new Regex(@"[1-9][0-9]{4,}"); //(腾讯QQ号从10000开始) //中国邮政编码 Regex reg = new Regex(@"[1-9]\d{5}(?!\d)");// (中国邮政编码为6位数字) //IP地址 Regex reg = new Regex(@"\d+\.\d+\.\d+\.\d+");// (提取IP地址时有用) //IP地址 Regex reg = new Regex(@"((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))"); 5.4 复杂需求表达式 1、截取最外层内容 a a 123

拿到上面的文本,要求结果如下:

a a

也就是去掉最后一个后面的字符串。

表达式为:(?= 0) return true; else return false; } /// /// 验证正整数 /// /// 待验证的字符串 /// 是否匹配 public static bool IsIntegerPositive(string input) { //string pattern = @"^[0-9]*[1-9][0-9]*$"; //return IsMatch(input, pattern); int i = 0; if (int.TryParse(input, out i) && i >= 1) return true; else return false; } /// /// 验证小数 /// /// 待验证的字符串 /// 是否匹配 public static bool IsDecimal(string input) { string pattern = @"^([-+]?[1-9]\d*\.\d+|-?0\.\d*[1-9]\d*)$"; return IsMatch(input, pattern); } /// /// 验证只包含英文字母 /// /// 待验证的字符串 /// 是否匹配 public static bool IsEnglishCharacter(string input) { string pattern = @"^[A-Za-z]+$"; return IsMatch(input, pattern); } /// /// 验证只包含数字和英文字母 /// /// 待验证的字符串 /// 是否匹配 public static bool IsIntegerAndEnglishCharacter(string input) { string pattern = @"^[0-9A-Za-z]+$"; return IsMatch(input, pattern); } /// /// 验证只包含汉字 /// /// 待验证的字符串 /// 是否匹配 public static bool IsChineseCharacter(string input) { string pattern = @"^[\u4e00-\u9fa5]+$"; return IsMatch(input, pattern); } /// /// 验证数字长度范围(数字前端的0计长度) /// [若要验证固定长度,可传入相同的两个长度数值] /// /// 待验证的字符串 /// 长度范围起始值(含) /// 长度范围结束值(含) /// 是否匹配 public static bool IsIntegerLength(string input, int lengthBegin, int lengthEnd) { //string pattern = @"^\d{" + lengthBegin + "," + lengthEnd + "}$"; //return IsMatch(input, pattern); if (input.Length >= lengthBegin && input.Length = lengthBegin && input.Length = lengthBegin && byteLength = lengthBegin && byteLength /// 验证网址(可以匹配IPv4地址但没对IPv4地址进行格式验证;IPv6暂时没做匹配) /// [允许省略"://";可以添加端口号;允许层级;允许传参;域名中至少一个点号且此点号前要有内容] /// /// 待验证的字符串 /// 是否匹配 public static bool IsURL(string input) { ////每级域名由字母、数字和减号构成(第一个字母不能是减号),不区分大小写,单个域长度不超过63,完整的域名全长不超过256个字符。在DNS系统中,全名是以一个点“.”来结束的,例如“www.nit.edu.cn.”。没有最后的那个点则表示一个相对地址。 ////没有例如"http://"的前缀,没有传参的匹配 //string pattern = @"^([0-9a-zA-Z][0-9a-zA-Z-]{0,62}\.)+([0-9a-zA-Z][0-9a-zA-Z-]{0,62})\.?$"; //string pattern = @"^(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?$"; string pattern = @"^([a-zA-Z]+://)?([\w-\.]+)(\.[a-zA-Z0-9]+)(:\d{0,5})?/?([\w-/]*)\.?([a-zA-Z]*)\??(([\w-]*=[\w%]*&?)*)$"; return IsMatch(input, pattern); } /// /// 验证IPv4地址 /// [第一位和最后一位数字不能是0或255;允许用0补位] /// /// 待验证的字符串 /// 是否匹配 public static bool IsIPv4(string input) { //string pattern = @"^(25[0-4]|2[0-4]\d]|[01]?\d{2}|[1-9])\.(25[0-5]|2[0-4]\d]|[01]?\d?\d)\.(25[0-5]|2[0-4]\d]|[01]?\d?\d)\.(25[0-4]|2[0-4]\d]|[01]?\d{2}|[1-9])$"; //return IsMatch(input, pattern); string[] IPs = input.Split('.'); if (IPs.Length != 4) return false; int n = -1; for (int i = 0; i < IPs.Length; i++) { if (i == 0 || i == 3) { if (int.TryParse(IPs[i], out n) && n > 0 && n < 255) continue; else return false; } else { if (int.TryParse(IPs[i], out n) && n >= 0 && n = -180 && lon = -90 && lat



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3