C#正则表达式根据分组命名取值

string[] regexList = new string[] {
                @"^(?<TickerPart1>[0-9A-Z])[ 0_]?(?<TickerPart2>[A-Z][0-9]) ?(COM(DTY)?|INDEX|IDX|IND|CURNCY|CUR|CLQ|ILQ|IDS)$",
                @"^(?<Ticker>[0-9A-Z]{2,5}[A-Z][0-9]) ?(COM(DTY)?|INDEX|IDX|IND|CURNCY|CUR)$",
                @"^(?<Ticker>[0-9A-Z]{2,5}[A-Z][0-9])$",
            };
string externalId = "3ABZ9 COMDTY";
//测试例子
//A Z9 INDEX;AZ9 CUR;A_H9 IDX;A0H9COM;ABZ9 INDEX;3ABZ9 COMDTY;ABZ9;3ABZ9
foreach (string regexString in regexList)
{
    if (Regex.IsMatch(externalId, regexString, RegexOptions.IgnoreCase))
    {
        Regex reg = new Regex(regexString, RegexOptions.IgnoreCase);
        Match mc = reg.Match(externalId);
        GroupCollection groups = mc.Groups;
        string convertid = "";
        foreach (string grn in reg.GetGroupNames())
        {
            if (grn.Contains("Ticker"))
          convertid += groups[grn].Value;
        }
        Console.WriteLine(convertid);
        break;
    }
}

以上例子将正则表达式中所有已经命名了的分组提取出来

C#正则表达式根据分组命名取值

上一篇:计算机硬盘


下一篇:APScheduler 定时任务工具的使用