首页 文章

C#中的正则表达式 - 我如何只替换Match中的一个特定组?

提问于
浏览
7

我正在使用C#regex解析文本 . 我想为每场比赛只替换一个特定组 . 我在这里是怎么做的:

void Replace(){
  string newText = Regex.Replace(File.ReadAllText(sourceFile), myRegex, Matcher, RegexOptions.Singleline);
  //.......   
}

void string Matcher(Match m){
  // how do I replace m.Groups[2] with "replacedText"?
  return ""; // I want to return m.Value with replaced m.Group[2]
}

6 回答

  • 4

    这应该这样做:

    string Matcher(Match m)
    {
        if (m.Groups.Count < 3)
        {
            return m.Value;
        }
    
        return string.Join("",  m.Groups
                                 .OfType<Group>() //for LINQ
                                 .Select((g, i) => i == 2 ? "replacedText" : g.Value)
                                 .Skip(1) //for Groups[0]
                                 .ToArray());
    }
    

    示例:http://rextester.com/DLGVPA38953

    EDIT: 虽然以上是您编写的问题的答案,但您可能会发现实际场景的零宽度外观更简单:

    Regex.Replace(input, @"(?<=e)l+(?=o)", replacement)
    

    示例:http://rextester.com/SOWWS24307

  • 5

    这个怎么样?

    static string Matcher(Match m)
        {
            var group = m.Groups[2];
            var startIndex = group.Index - m.Index;
            var length = group.Length;
            var original = m.Value;
            var prior = original.Substring(0, startIndex);
            var trailing = original.Substring(startIndex + length);
            return string.Concat(prior, "replacedText", trailing);
        }
    
  • 0

    您可以使用 MatchEvaluator :试试这个 .

    var replaced = Regex.Replace(text, pattern, m => m.Groups[1] + "AA" + m.Groups[3]);
    

    我在stackoverflow中发现了一个与此相关的帖子:watch This

  • 10

    Regex.Replace 将始终替换所提供的正则表达式 matched 的所有内容 .

    你有两种可能性:

    • 仅匹配您要替换的内容

    要么

    • 使用捕获组将已匹配但应保留的原始字符串部分插入替换字符串中 .

    您提供的信息不足以更具体地回答您的问题 . 例如 . 你真的需要 MatchEvaluator 吗?如果您想为每场比赛提供单独的替换字符串,则仅需要这样做 .

  • 2
    private string ReplaceText(string originalText)
        {
            string replacedText = null;
    
            Regex regEx = new Regex("[your expression here]");
    
            Match match = regEx.Match(originalText);
    
            if (match.Success)
            {
                Group matchGroup = match.Groups[2];
    
                //[first part of original string] + [replaced text] + [last part of original string]
                replacedText =
                    $"{originalText.Substring(0, matchGroup.Index)}[Your replaced string here]{originalText.Substring(matchGroup.Index + matchGroup.Length)}";
    
            }
            else
                replacedText = originalText;
    
            return replacedText;
        }
    
  • 0

    下面的代码将匹配并根据groupValues集合构造替换字符串 . 此集合指定组索引和用其替换值的文本 .

    与其他解决方案不同,它不需要将整个匹配包含在组中,只需要包含要在组中匹配的部分 .

    public static string ReplaceGroups(Match match, Dictionary<int, string> groupValues)
    {
        StringBuilder result = new StringBuilder();
    
        int currentIndex = 0;
        int offset = 0;
    
        foreach (KeyValuePair<int, string> replaceGroup in groupValues.OrderBy(x => x.Key))
        {
            Group group = match.Groups[replaceGroup.Key];
    
            if (currentIndex < group.Index)
            {
                result.Append(match.Value.Substring(currentIndex, group.Index - match.Index - currentIndex));
            }
    
            result.Append(replaceGroup.Value);
    
            offset += replaceGroup.Value.Length - group.Length;
            currentIndex = group.Index - match.Index + group.Length;
        }
    
        return result.ToString();
    }
    

相关问题