C#正则表达式:初学者完整指南
正则表达式(regular expressions,regex)是一种强大的工具,用于根据指定模式搜索、替换和验证字符串。在C# (.NET)中,通过System.Text.RegularExpressions命名空间实现正则表达式的操作。本文将从创建最简单的模式到使用Regex类的全部功能,帮助您掌握基础知识。
1. C#中Regex的基础用法
首先,引入命名空间:
using System.Text.RegularExpressions;Regex类提供了静态方法和实例方法。检查字符串是否包含匹配模式的子串的最简单方法是使用IsMatch方法:
string text = "你好,我的邮箱:test@example.com";string pattern = @"\\w+@\\w+\\.\\w+"; // 简单的邮箱模式
bool hasEmail = Regex.IsMatch(text, pattern);Console.WriteLine(hasEmail); // True模式解析:
\\w+— 一个或多个字母、数字或下划线@— “@”符号\\.— 转义的点(未转义的点表示“任意字符”)
对于重复调用,最好创建Regex对象,以避免重复编译模式:
Regex emailRegex = new Regex(@"\\w+@\\w+\\.\\w+");Console.WriteLine(emailRegex.IsMatch("admin@site.ru")); // True2. 查找所有匹配项:Match和MatchCollection
Match方法返回第一个匹配项,而Matches返回所有匹配项的集合MatchCollection。每个Match对象包含有关找到的子串、其位置和长度的信息。
示例:从字符串中提取所有数字
string data = "2023年发生了15个事件,2024年已有23个。";string numberPattern = @"\\d+"; // 一个或多个数字
MatchCollection matches = Regex.Matches(data, numberPattern);
foreach (Match match in matches){ Console.WriteLine($"找到:{match.Value} 在位置 {match.Index}");}// 输出:// 找到:2023 在位置 0// 找到:15 在位置 10// 找到:2024 在位置 20// 找到:23 在位置 31使用组(Group)。组允许提取匹配项的部分内容。例如,在搜索“dd.mm.yyyy”格式的日期时,可以分别获取日、月和年:
string input = "今天是25.12.2024";string datePattern = @"(\\d{2})\\.(\\d{2})\\.(\\d{4})";
Match match = Regex.Match(input, datePattern);if (match.Success){ Console.WriteLine($"日:{match.Groups[1].Value}"); // 25 Console.WriteLine($"月:{match.Groups[2].Value}"); // 12 Console.WriteLine($"年:{match.Groups[3].Value}"); // 2024}组从1开始编号(组0是整个匹配项)。命名组更易于阅读:
string namedPattern = @"(?<day>\\d{2})\\.(?<month>\\d{2})\\.(?<year>\\d{4})";match = Regex.Match(input, namedPattern);Console.WriteLine(match.Groups["day"].Value); // 253. 高级功能:替换和选项
使用Regex.Replace进行文本替换。不仅可以删除或替换子串,还可以在替换字符串中使用组:
string phone = "+7 (123) 456-78-90";// 去掉除数字外的所有字符string clean = Regex.Replace(phone, @"[^\\d]", "");Console.WriteLine(clean); // 71234567890
// 更改格式:(123) 456-78-90 → 123-456-7890string formatted = Regex.Replace(phone, @"\\((\\d{3})\\)\\s*(\\d{3})-(\\d{2})-(\\d{2})", "$1-$2-$3$4");Console.WriteLine(formatted); // 123-456-7890重要选项(RegexOptions):