【问题标题】:C# Enumerate Regex MatchesC# 枚举正则表达式匹配
【发布时间】:2014-02-27 12:40:45
【问题描述】:

在 C# 中枚举正则表达式替换的最佳方法是什么。

例如,如果我希望将每个 " 匹配项替换为 "。 # 号是递增数字。最好的编码方式是什么?

【问题讨论】:

    标签: c# regex string replace pattern-matching


    【解决方案1】:

    您可以在指定为MatchEvaluator 回调的匿名方法中使用递增计数器。 (?<=…) 是积极的向后看;它由正则表达式评估器匹配,但没有被删除。

    string input = "a <intent-filter data=a /> <intent-filter data=b />";
    int count = 0;
    string result = Regex.Replace(input, @"(?<=\<intent-filter)", 
        _ => " android:label=label" + count++);
    

    【讨论】:

    • +1 :-) 哦!闪亮的!可能是_ (match) =&gt; " android:label=label" + count++);?因为msdn.microsoft.com/en-us/library/…
    • @DarenThomas: _ 被用作匿名方法中参数名称的事实上约定,不会在方法主体中使用。您可以改用match =&gt;
    • 啊!你说得对!这就是这样的“我也知道!”我的时刻。捂脸!这是正确答案!
    • 您的代码有效,但我不明白您如何能够在没有匹配的情况下向后看。在你的括号之后或之前没有任何东西,你能解释一下这是怎么可能的……如果有必要看看后面的匹配项是什么?
    • @userX:始终匹配空的正则表达式模式(通过任何零宽度子字符串)。例如,Regex.Replace("abc", "", "1") 将在字符串中的所有位置匹配,得到结果"1a1b1c1"。如果我们“预先”回顾我们的空模式,我们可以限制匹配的位置。例如,Regex.Replace("abc", "(?&lt;=b)", "1") 确保仅匹配b 之后的位置,给出结果"ab1c"
    【解决方案2】:

    不要为这个使用正则表达式。做一些类似的事情:

    var pieces = text.Split(new string[] { "xx" });
    var sb = new StringBuilder();
    var idx = 0;
    foreach (var piece in pieces)
    {
        sb.Append(piece);
        sb.Append(" android:label=label");
        sb.Append(idx);
    }
    // oops, homework assignment: remove the last "<intent-filter android:label=label#"
    

    【讨论】:

      猜你喜欢
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      相关资源
      最近更新 更多