闽公网安备 35020302035485号
广泛应用:几乎所有的编程语言都支持正则表达式,使得它在跨平台应用中非常有用。
复杂的正则表达式可能难以理解和维护。建议在使用时添加必要的注释,并尽量将复杂的模式拆分成多个简单的部分。
/// <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>
/// 堆代码 duidaima.com
/// 验证手机号码
/// </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.
}
分割字符串 /// <summary>
/// 分割字符串
/// </summary>
public static void SplitString()
{
string pattern = @"[;,]";
string input = "apple;banana,orange;grape";
var regex = new Regex(pattern);
string[] substrings = regex.Split(input);
foreach (string substring in substrings)
{
Console.WriteLine(substring);
//Output:
//apple
//banana
//orange
//grape
}
}
C#正则性能提升技巧string pattern = @"(\d{4})/(\d{2})/(\d{2})";
Regex regex = new Regex(pattern, RegexOptions.Compiled);
避免过度回溯// 贪婪匹配 string pattern = @"<.*>"; // 非贪婪匹配 string pattern = @"<.*?>";合理设置超时时间
string pattern = @"(\d{4})/(\d{2})/(\d{2})";
TimeSpan timeout = TimeSpan.FromSeconds(1); // 设置1秒的超时时间
Regex regex = new Regex(pattern, RegexOptions.None, timeout);