代码之家  ›  专栏  ›  技术社区  ›  Brian

提取匹配的组名:更干净的方法?

  •  1
  • Brian  · 技术社区  · 14 年前

    假设我有一个模式 "((?<happy>foo)|(?<sad>bar)|...)" . 可能还有更多的条件。如果我想知道我找到了哪个分组(例如搜索 12bar34 将返回 "sad" 有没有比我现在拥有的代码更干净的方法来完成它?

    Regex objRegex = new Regex("((?<happy>foo)|(?<sad>bar))");
    Match objMatch = objRegex.Match("12bar34");        
    for (int i = 0; i < objMatch.Groups.Count; ++i)
    {
        int tmp;
        if (!String.IsNullOrEmpty(objMatch.Groups[i].Value) &&
            !Int32.TryParse(objRegex.GroupNameFromNumber(i), out tmp))
        {
            //The name of the grouping.
            Trace.WriteLine(objRegex.GroupNameFromNumber(i));
        }
    }
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   Ani    14 年前
    foreach(string groupName in objRegex.GetGroupNames())
    {
       if (objMatch.Groups[groupName].Success)
          Trace.WriteLine(groupName);
    }
    

    Regex.GetGroupNames "0"