【问题标题】:Regular expressions .Net Regex.Replace正则表达式 .Net Regex.Replace
【发布时间】:2012-11-22 03:42:18
【问题描述】:

是否可以将命名匹配替换为某个常量值或另一个命名匹配? 假设我有输入字符串,如果它包含“123”,则将“123”替换为“567” 如果字符串有“234”,我希望它替换为“678”。我需要使用 Regex.Replace 来做到这一点,因为我使用的 API 使用 Regex.Replace 并且更改该 API 不是我想要的。

所以我为那个 API matchPattern 和 replacePattern 提供了什么来获得类似的东西:

Regex.Replace("123", matchPattern, replacePattern) 返回“567”

Regex.Replace("234", matchPattern, replacePattern) 返回“678”

【问题讨论】:

  • 那么你的意思是你想传入一个固定的replacePattern,它会根据输入做不同的事情?
  • 为什么不只执行两个 Regex.Replace 命令?

标签: .net regex


【解决方案1】:

仅使用正则表达式替换调用是不可能的。但是可以提供回调函数:

public String Replacer(Match m) {
    if (m.Groups[0].Value == "123")
       return "567";
    else if (m.Groups[0].Value == "456")
       return "678";
}

resultString = Regex.Replace(subject, @"\b(?:123|456)\b", new MatchEvaluator(Replacer));

【讨论】:

    【解决方案2】:

    我希望还有其他方法可以做到这一点,但我想出了以下使用 named groupsanonymous methods 的方法。

    在我的示例中,我假设 123、456、789 将分别替换为 111、444、777,而字符串中的 000 将保持不变。

    我对@9​​87654323@ 使用了一种方法,该值将用作a replacement value。例如在这部分:

    (?123) = 值 123 将被 111 替换,其中 111 也是组的名称。

    因此,一般模式将变为:(?<ValueToReplace>ValueToSearch)

    这是一个示例代码:

    Dim sampleText = "123 456 789 000"
    Dim re As New Regex("\b(?<111>123)\b|\b(?<444>456)\b|\b(?<777>789)\b")
    Dim count As Integer = re.Matches(sampleText).Count
    Dim contents As String = re.Replace(sampleText, New MatchEvaluator(Function(c) re.GetGroupNames().Skip(1).ToArray().GetValue(c.Captures(0).Index Mod count).ToString()))
    

    根据您的方法,我希望您在 VB.Net 中工作,但我也附上了 C# 版本。

    这里是 C# 版本:

    var sampleText = @"123 456 789 000";
    Regex re = new Regex(@"\b(?<111>123)\b|\b(?<444>456)\b|\b(?<777>789)\b");
    int count = re.Matches(sampleText).Count;
    string contents = re.Replace(sampleText, new MatchEvaluator((c) => re.GetGroupNames().Skip(1).ToArray().GetValue(c.Captures[0].Index % count).ToString()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多