C# 如何使用正则表达式进行字符串匹配_C# 正则表达式字符串匹配教程

来源:这里教程网 时间:2026-02-21 17:31:36 作者:

在 C# 中使用正则表达式进行字符串匹配,主要依赖于 System.Text.RegularExpressions.Regex 类。这个类提供了丰富的静态和实例方法,可以用来验证、搜索、替换和分割字符串。下面是一个清晰的教程,帮助你快速掌握 C# 正则表达式的基本用法。

1. 引入命名空间

使用正则表达式前,需要引入以下命名空间:

using System.Text.RegularExpressions;

2. 常用方法介绍

Regex.IsMatch:判断字符串是否匹配指定模式。

例如:检查一个字符串是否为有效的手机号(以中国大陆为例):

string input = "13812345678";
string pattern = @"^1[3-9]\d{9}$";
bool isMatch = Regex.IsMatch(input, pattern);
Console.WriteLine(isMatch); // 输出 True

Regex.Match:返回第一个匹配的结果(Match 对象),可用于提取信息。

例如:从一段文本中提取第一个邮箱地址:

string text = "联系我:admin@example.com 或 support@domain.org";
string emailPattern = @"[\w.-]+@[\w.-]+\.\w+";
Match match = Regex.Match(text, emailPattern);
if (match.Success)
{
   Console.WriteLine("找到邮箱:" + match.Value);
}

Regex.Matches:返回所有匹配项(MatchCollection),适合提取多个结果。

例如:提取文本中所有邮箱:

MatchCollection matches = Regex.Matches(text, emailPattern);
foreach (Match m in matches)
{
   Console.WriteLine(m.Value);
}

Regex.Replace:替换匹配到的内容。

例如:隐藏手机号中间四位:

string phone = "13812345678";
string masked = Regex.Replace(phone, @"(\d{3})\d{4}(\d{4})", "$1****$2");
Console.WriteLine(masked); // 输出 138****5678

Regex.Split:按正则表达式分割字符串。

例如:用非字母字符分割文本:

string sentence = "hello, world! how are you?";
string[] words = Regex.Split(sentence, @"[^a-zA-Z]+");
foreach (string word in words)
{
   if (!string.IsNullOrEmpty(word))
      Console.WriteLine(word);
}

3. 常见正则表达式模式示例

以下是一些常用的正则表达式模式:

邮箱
@"^[\w.-]+@[\w.-]+\.\w+$"
手机号(中国)
@"^1[3-9]\d{9}$"
身份证号(18位)
@"^\d{17}[\dXx]$"
数字(整数)
@"^\d+$"
URL
@"^https?:\/\/[\w.-]+(\.[\w.-]+)+[/\w.-]*"

4. 注意事项与性能建议

如果同一个正则表达式会被多次使用,建议创建 Regex 实例并设置 RegexOptions.Compiled 提升性能:

Regex phoneRegex = new Regex(@"^1[3-9]\d{9}$", RegexOptions.Compiled);
bool result = phoneRegex.IsMatch("13900001111");

对于大小写不敏感的匹配,可使用 RegexOptions.IgnoreCase

基本上就这些。C# 的正则表达式功能强大且易于集成,只要熟悉常用语法和方法,就能高效处理各种字符串匹配任务。

相关推荐

热文推荐