代码之家  ›  专栏  ›  技术社区  ›  Kevin Davis

使用MatchEvaluator委托生成列表而不使用类变量?

  •  1
  • Kevin Davis  · 技术社区  · 17 年前

    背景:

    我在C工作#

    文本看起来像:

    The dog ate 3 cats and felt ill <ref name="something">http://cateater.com</ref>
    

    <ref> s、 将它们放入散列中,稍后我可以将其呈现为引用列表。

    问题:

    这个 example on MSDN 使用一个类变量来实现这一点,但我希望有一个更优雅的解决方案。

    2 回复  |  直到 17 年前
        1
  •  3
  •   AnthonyWJones    17 年前

    如果没有,则可以使用匿名方法有效地对MatchEvaluator委托进行参数化功能:-

    MatchEvaluator evaluator = delegate(Match m)
    {
        // code to return replacement
        // this code uses and modifies lookups
    }
    
    Dictionary<string, string> lookups = new Dictionary<string, string>();
    sOutput = someRegex.Replace(sInput, evaluator);
    
        2
  •  0
  •   Devos    12 年前

    使用以下命令获取引用列表:

    var srcmatches = Regex.Matches(src, "<ref .*?>(.*?)</ref>");
    
    List<string> refs = srcmatches.OfType<Match>().Select(x => x.Groups[1].ToString()).ToList();
    

    首先它匹配 <ref>