C# 使用正则表达式

发布于:2025-06-08 ⋅ 阅读:(16) ⋅ 点赞:(0)

C# 使用正则表达式

/// <summary>
/// 测试正则表达式
/// </summary>
private static void test022()
{
    //检查是否匹配:Regex.IsMatch(currencyValue, pattern); 或 new Regex(...).IsMatch(currencyValue)
    string pattern = @"\d{3,}";
    bool b = Regex.IsMatch("98", pattern);
    Console.WriteLine(b);
    //Match方法返回第一个匹配项。例如,从一段文本中获取第一个符合电子邮件格式的字符串(简单示例)。
    string text = "我的邮箱是test@example.com,还有一个无效邮箱abc";
    Regex emailRegex = new Regex(@"[a-zA-Z0-9_.]+@[a-zA-Z0-9_.]+\.[a-zA-Z]+");
    Match match = emailRegex.Match(text);
    if (match.Success)
    {
        Console.WriteLine("找到的邮箱是: " + match.Value);
    }
    //Matches方法返回所有匹配项的集合。例如,从一段文本中获取所有的数字。
    string numberText = "abc123def456";
    Regex numberRegex = new Regex(@"\d+");
    MatchCollection matches = numberRegex.Matches(numberText);
    foreach (Match m in matches)
    {
        Console.WriteLine(m.Value);
    }
    //分组(Grouping):使用括号()可以将正则表达式的一部分进行分组。
    //分组可以用于提取匹配的特定部分或者在匹配过程中应用量词到一组字符上。
    //例如,在匹配日期格式(假设为yyyy-MM-dd)时,可以这样分组来提取年、月、日。
    string dateText = "2024-05-10";
    Regex dateRegex = new Regex(@"(\d{4})-(\d{2})-(\d{2})");
    Match match2 = dateRegex.Match(dateText);
    if (match2.Success)
    {
        Console.WriteLine("年: " + match2.Groups[1].Value);
        Console.WriteLine("月: " + match2.Groups[2].Value);
        Console.WriteLine("日: " + match2.Groups[3].Value);
    }
    //零宽断言(Zero - width Assertions):这是一种特殊的匹配方式,它不消耗字符,只是在某个位置进行断言。
    //例如,(?=...)是正向肯定预查,它用于查找后面跟着特定模式的位置。假设要找到后面跟着abc的数字,可以这样写:\d(?=abc)
    //\d{2}(?=19)   // 匹配位置必须 ‌后面面紧跟着‌ "19" 
    //\d{2}(?!19)   // 匹配位置必须 ‌后面面紧跟着‌ 不是"19" 
    //(?<=19)\d{2}  // 匹配位置必须 ‌前面紧跟着‌ "19" 
    //(?<!19)\d{2}  // 匹配前面不是"19"的两位数字
    string assertText = "1abc2def";
    Regex assertRegex = new Regex(@"\d(?=abc)");//找到后面跟着abc的数字
    //Regex assertRegex = new Regex(@"\d(?!abc)");//找到后面跟着非abc的数字
    //Regex assertRegex = new Regex(@"(?<=abc)\d");//找到前面跟着abc的数字
    //Regex assertRegex = new Regex(@"(?<!abc)\d");//找到前面跟着非abc的数字
    MatchCollection matches2 = assertRegex.Matches(assertText);
    foreach (Match ma in matches2)
    {
        Console.WriteLine(ma.Value);//
    }
    Console.WriteLine("--------------------------------");
    // 替换replace
    var source = "123abc456ABC789";
    // 静态方法
    //var newSource=Regex.Replace(source,"abc","|",RegexOptions.IgnoreCase);
    // 实例方法
    Regex regex = new Regex("abc", RegexOptions.IgnoreCase);
    var newSource = regex.Replace(source, "|");
    Console.WriteLine("原字符串:" + source);
    Console.WriteLine("替换后的字符串:" + newSource);
    
}

参考:
https://blog.csdn.net/weixin_39604653/article/details/144316052
https://www.cnblogs.com/sosoft/p/regexMatch.html
https://www.runoob.com/csharp/csharp-regular-expressions.html