正则表达式用于字符串模式匹配(如手机号、邮箱、密码验证),C# 中通过 Regex 类实现。
using System.Text.RegularExpressions;
public class RegexHelper
{
// 验证手机号(中国大陆)
public static bool IsPhoneNumber(string phone)
{
if (string.IsNullOrEmpty(phone)) return false;
// 正则表达式:1开头,11位数字
string pattern = @"^1[3-9]\d{9}$";
return Regex.IsMatch(phone, pattern);
}
// 验证邮箱
public static bool IsEmail(string email)
{
if (string.IsNullOrEmpty(email)) return false;
string pattern = @"^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z0-9]{2,4}$";
return Regex.IsMatch(email, pattern);
}
// 验证密码(8-20位,含字母和数字)
public static bool IsValidPassword(string password)
{
if (string.IsNullOrEmpty(password)) return false;
string pattern = @"^(?=.*[A-Za-z])(?=.*\d).{8,20}$";
return Regex.IsMatch(password, pattern);
}
// 提取字符串中的数字
public static string ExtractNumbers(string str)
{
if (string.IsNullOrEmpty(str)) return "";
return Regex.Replace(str, @"[^\d]", "");
}
}
// 调用示例
Console.WriteLine("手机号验证:" + RegexHelper.IsPhoneNumber("13800138000")); // True
Console.WriteLine("邮箱验证:" + RegexHelper.IsEmail("test@example.com")); // True
Console.WriteLine("密码验证:" + RegexHelper.IsValidPassword("Csharp123")); // True
Console.WriteLine("提取数字:" + RegexHelper.ExtractNumbers("C#编程123教程456")); // 123456