C#正则表达式实例详解:从理论到实践
\n\n正则表达式(regex)是一种强大的工具,用于按模式搜索、提取和替换文本。在C#(.NET)中,正则表达式的操作通过命名空间System.Text.RegularExpressions和Regex类实现。本文将通过实际示例讲解主要功能:从简单搜索到邮箱和手机号验证。
1. 基础:Regex类及其方法
\n\n核心操作类是Regex。它提供静态方法和实例方法。以下是主要方法:
- \n
IsMatch— 检查字符串是否包含与模式匹配的内容。 \nMatch— 查找第一个匹配项。 \nMatches— 查找所有匹配项。 \nReplace— 将匹配项替换为指定字符串。 \nSplit— 按模式拆分字符串。 \n
示例1. 简单检查
\nusing System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n static void Main()\n {\n string text = "你好,我的号码:123-456-7890";\n string pattern = @"\\d{3}-\\d{3}-\\d{4}";\n\n if (Regex.IsMatch(text, pattern))\n {\n Console.WriteLine("号码已找到!");\n }\n }\n}\n\n\n在此示例中,\\d{3}表示“恰好三位数字”。反斜杠通过@(逐字字符串)进行转义。
2. 捕获组与数据提取
\n\n捕获组允许提取匹配的部分。它们由圆括号()定义。每个组都有一个序号(从1开始)。
示例2. 从邮箱中提取用户名和域名
\nstring email = "user@example.com";\nstring pattern = @"^(\\w+)@(\\w+\\.\\w+)$";\n\nMatch match = Regex.Match(email, pattern);\n\nif (match.Success)\n{\n Console.WriteLine($"用户名:{match.Groups[1].Value}"); // user\n Console.WriteLine($"域名:{match.Groups[2].Value}"); // example.com\n}\n\n\n这里(\\w+)捕获一个或多个字母数字字符。^和$是字符串开头和结尾的锚点。
示例3. 解析URL
\nstring url = "https://pythonlib.ru/page?id=42";\nstring pattern = @"^(https?)://([^/]+)(/.*)?$";\n\nMatch m = Regex.Match(url, pattern);\nif (m.Success)\n{\n Console.WriteLine($"协议:{m.Groups[1].Value}"); // https\n Console.WriteLine($"域名:{m.Groups[2].Value}"); // pythonlib.ru\n Console.WriteLine($"路径:{m.Groups[3].Value}"); // /page?id=42\n}\n\n\n3. 文本替换与删除
\n\nReplace方法允许替换找到的片段。可以使用$1、$2等反向引用来插入组。
示例4. 格式化电话号码
\nstring raw = "89161234567";\nstring pattern = @"(\\d{1})(\\d{3})(\\d{3})(\\d{2})(\\d{2})";\nstring replacement = "+7 ($2) $3-$4-$5";\n\nstring formatted = Regex.Replace(raw, pattern, replacement);\nConsole.WriteLine(formatted); // +7 (916) 123-45-67\n\n\n示例5. 删除多余空格
\nstring text = "这是 一段 包含 多余 空格的文本。";\nstring cleaned = Regex.Replace(text, @"\\s+", " ");\nConsole.WriteLine(cleaned); // "这是一段包含多余空格的文本。"\n\n\n\\s+ — 一个或多个空白字符。替换为单个空格。
4. 实际案例:邮箱和手机号验证
\n\n在实际应用中,正则表达式最常用于验证用户输入。下面给出两个典型示例。
\n\n邮箱验证(简化版)
\npublic static bool IsValidEmail(string email)\n{\n if (string.IsNullOrWhiteSpace(email))\n return false;\