C# 中的正则表达式:强大的文本处理工具
正则表达式是根据给定模式搜索、提取和替换文本数据不可或缺的工具。在 C# (.NET) 中,通过强大的命名空间 System.Text.RegularExpressions 和 Regex 类实现对正则表达式的支持。本文将结合实际示例探讨 C# 正则表达式的主要功能,这些示例将帮助您自动化字符串处理。
C# 中 Regex 类的基础
C# 中用于处理正则表达式的主要类是 System.Text.RegularExpressions.Regex。它提供了用于执行搜索、替换和字符串分割操作的静态方法和实例方法。
创建 Regex 对象
您可以通过向构造函数传递模式以及可选的标志来创建 Regex 类的实例:
using System.Text.RegularExpressions;
// 简单创建Regex regex = new Regex(@"\\d+");
// 带标志(例如,忽略大小写)Regex regexIgnoreCase = new Regex(@"hello", RegexOptions.IgnoreCase);重要提示: 在 C# 中,建议使用逐字字符串(带有 @ 前缀)来编写模式。这可以避免转义反斜杠,使代码更具可读性。
Regex 的静态方法
对于一次性操作,使用无需创建类实例的静态方法更为方便:
bool isMatch = Regex.IsMatch("Hello, world!", @"world");Console.WriteLine(isMatch); // 真
string result = Regex.Replace("123abc456", @"\\d+", "X");Console.WriteLine(result); // XabcX处理文本的主要方法
Regex 类提供了四个关键方法:IsMatch、Match、Matches 和 Split。让我们通过示例逐一介绍。
IsMatch 方法 — 检查匹配
IsMatch 方法返回一个 bool 值,指示在字符串中是否至少找到一个与模式匹配的内容。
string email = "user@example.com";string pattern = @"^[\\w\\.-]+@[\\w\\.-]+\\.\\w{2,4}$";
if (Regex.IsMatch(email, pattern)){ Console.WriteLine("电子邮件有效");}else{ Console.WriteLine("电子邮件无效");}此示例检查字符串是否与简单的电子邮件地址模式匹配。
Match 和 Matches 方法 — 查找匹配项
Match 返回第一个匹配项,而 Matches 以 MatchCollection 对象的形式返回所有匹配项的集合。
string text = "价格:1500 卢布。折扣:200 卢布。总计:1300 卢布。";string pattern = @"\\d+";
// 第一个匹配项Match firstMatch = Regex.Match(text, pattern);Console.WriteLine($"第一个数字:{firstMatch.Value}"); // 1500
// 所有匹配项MatchCollection allMatches = Regex.Matches(text, pattern);Console.WriteLine("所有数字:");foreach (Match match in allMatches){ Console.WriteLine($" - {match.Value}"); // 1500, 200, 1300}Match 对象不仅包含值 (Value),还包含在字符串中的位置 (Index) 和长度 (Length)。
Split 方法 — 分割字符串
Regex.Split 根据指定的模式将字符串分割成子字符串数组。它类似于 String.Split,但支持正则表达式。
string data = "John;25;莫斯科;程序员";string pattern = @";";
string[] parts = Regex.Split(data, pattern);foreach (string part in parts){ Console.WriteLine(part);}// 输出:// John// 25// 莫斯科// 程序员分组和捕获数据
正则表达式最强大的功能之一