C# 正则表达式实战示例

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

C# 正则表达式实战示例



正则表达式(regex)是一种强大的工具,用于按模式搜索、验证和替换文本。在 C# (.NET) 中,通过 System.Text.RegularExpressions.Regex 类实现。本文将通过真实示例讲解主要功能:从简单的邮箱验证到从 HTML 中提取数据。所有示例均可直接复制并在您的项目中使用。



C# 中 Regex 的基础用法



Regex 类提供三个关键方法:

  • IsMatch — 检查字符串是否匹配模式;
  • Match — 查找第一个匹配项;
  • Matches — 查找所有匹配项。


简单示例 — 检查字符串是否包含数字:



using System;using System.Text.RegularExpressions;

public class RegexExample{ public static void Main() { string text = "我的号码: 12345"; string pattern = @"\\d+"; // 一个或多个数字

bool hasDigits = Regex.IsMatch(text, pattern); Console.WriteLine(hasDigits); // True }}


注意字符串前的 @ — 这是逐字字符串字面量,用于禁用反斜杠转义。没有它,则需要写成 "\\\\d+"。



验证邮箱和电话号码



邮箱验证

邮箱验证是经典任务。一个简单但有效的模式:



public static bool IsValidEmail(string email){    string pattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";    return Regex.IsMatch(email, pattern);}

// 使用示例Console.WriteLine(IsValidEmail("user@example.com")); // TrueConsole.WriteLine(IsValidEmail("user@.com")); // False


模式解析:

  • ^ — 字符串开头;
  • [a-zA-Z0-9._%+-]+ — 本地部分(字母、数字和特殊字符);
  • @ — @ 符号;
  • [a-zA-Z0-9.-]+ — 域名;
  • \\. — 点号(已转义);
  • [a-zA-Z]{2,} — 顶级域名(至少2个字母);
  • $ — 字符串结尾。


电话号码验证

俄罗斯格式示例(+7 XXX XXX-XX-XX):



public static bool IsValidRussianPhone(string phone){    string pattern = @"^\\+7\\d{3}\\d{3}-\\d{2}-\\d{2}$";    // 或更灵活的版本:    // @"^\\+7[\\s-]?\\d{3}[\\s-]?\\d{3}[\\s-]?\\d{2}[\\s-]?\\d{2}$"    return Regex.IsMatch(phone, pattern);}


使用捕获组从文本中提取数据



捕获组(括号 ())允许提取匹配的部分。例如,从文本中提取所有邮箱:



string text = "联系方式: support@site.com, admin@test.org, info@company.net";string pattern = @"([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,})";

MatchCollection matches = Regex.Matches(text, pattern);foreach (Match match in matches){ Console.WriteLine($"完整邮箱: {match.Value}"); Console.WriteLine($"本地部分: {match.Groups[1].Value}"); Console.WriteLine($"域名: {match.Groups[2].Value}"); Console.WriteLine($"顶级域: {match.Groups[3].Value}"); Console.WriteLine("---");}


结果:

完整邮箱: support@site.com本地部分: support域名: site顶级域: com---


组从1开始编号(组0为整个匹配)。也可以为组命名:



string pattern = @"(?<user>[a-zA-Z0-9._%+-]+)@(?<domain>[a-zA-Z0-9.-]+)\\.(?<tld>[a-zA-Z]{2,})";// 访问: match.Groups["user"].Value


从 HTML 中提取链接



string html = @"<a href='https://example.com'>Examp                

博客

书籍推荐