在正则表达式内设定选项

阅读 11

2022-04-14

string pattern = "(?i:[A-Z])\\d";//指定括号中的组不区分大小写
    string str = "A1 2b c2 3D";
    Regex regex = new Regex(pattern);
    MatchCollection matchCollection = regex.Matches(str);
    foreach (var item in matchCollection)
    {
        Console.WriteLine(item);
    }

    Console.WriteLine();
    pattern = "([A-Z])\\d";//
    str = "A1 2b c2 3D";
    regex = new Regex(pattern);
    matchCollection = regex.Matches(str);
    foreach (var item in matchCollection)
    {
        Console.WriteLine(item);
    }

    Console.WriteLine();
    pattern = "(?-i:[A-Z])\\d";指定括号中的组区取消了不区分大小写
    str = "A1 2b c2 3D";
    regex = new Regex(pattern);
    matchCollection = regex.Matches(str);
    foreach (var item in matchCollection)
    {
        Console.WriteLine(item);
    }


    Console.WriteLine();
    pattern = "([A-Z])\\d";//
    str = "A1 2b C2 3D";
    regex = new Regex(pattern);
    matchCollection = regex.Matches(str);
    foreach (Match  item in matchCollection)
    {
      GroupCollection groupCollection=  item.Groups ;
        foreach (Group subItem in groupCollection )
        {
            Console.WriteLine($"group{subItem .Value }");
        }
    }

    Console.WriteLine();
    pattern = "(?n:[A-Z])\\d";//指定了只有显示命名或者编号的组才是有效的组
    str = "A1 2b C2 3D";
    regex = new Regex(pattern);
    matchCollection = regex.Matches(str);
    foreach (Match item in matchCollection)
    {
        GroupCollection groupCollection = item.Groups;
        foreach (Group subItem in groupCollection)
        {
            Console.WriteLine($"group{subItem.Value }");
        }
    }


    Console.WriteLine();
    pattern = "(?<firstGroup>[A-Z])\\d";//指定了组的名称
    str = "A1 2b C2 3D";
    regex = new Regex(pattern ,RegexOptions.ExplicitCapture );//指定了只有显示命名或者编号的组才是有效的组
    matchCollection = regex.Matches(str);
    foreach (Match item in matchCollection)
    {
        GroupCollection groupCollection = item.Groups;
        foreach (Group subItem in groupCollection)
        {
            Console.WriteLine($"group{subItem.Value }");
        }
    }

精彩评论(0)

0 0 举报