/// <summary> /// 验证邮箱地址 /// </summary> public static void VerifyEmailAddress() { string email = "edwin.doe@qq.com"; string pattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"; var regex = new Regex(pattern); bool isValid = regex.IsMatch(email); Console.WriteLine($"{email} is valid email address: {isValid}"); }
验证手机号码
/// <summary> /// 验证手机号码 /// </summary> public static void VerifyMobilePhone() { string mobile = "13812345678"; string pattern = @"^1[3-9]\d{9}$"; var regex = new Regex(pattern); bool isValid = regex.IsMatch(mobile); Console.WriteLine($"{mobile} is valid mobile phone number: {isValid}"); }
提取URL
/// <summary> /// 提取URL /// </summary> public static void ExtractUrl() { string url = "https://github.com/YSGStudyHards/DotNetGuide"; string pattern = @"^https?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+$"; var regex = new Regex(pattern); Match match = regex.Match(url); if (match.Success) { Console.WriteLine($"Found URL: {match.Value}"); //Output:https://github.com/YSGStudyHards/DotNetGuide } else { Console.WriteLine("No URL found."); } }
替换文本
/// <summary> /// 替换文本 /// </summary> public static void ReplaceText() { string input = "The date is 2024/12/16."; string pattern = @"(\d{4})/(\d{2})/(\d{2})"; string replacement = "$1-$2-$3"; var regex = new Regex(pattern); string result = regex.Replace(input, replacement); Console.WriteLine(result);//Output:The date is 2024-12-16. }