如何仅替换 Regex.Replace 中的捕获组?

How to replace only capturing group in Regex.Replace?

我有一个以键为模式、替换为值的字典。每个模式都有一个捕获组。我想用替换项替换 ONLY 捕获组。我的尝试如下,但当然它正在取代整个模式。我仅限于 .NET 3.5。不确定我是否在正确的轨道上。

        string xml = "abc def ghi blabla horse 123 jakljd alj ldkfj s;aljf kljf sdlkj flskdjflskdjlf lskjddhcn guffy";
        Dictionary<string, string> substitutions = new Dictionary<string, string> 
        { 
            {"abc (.+) ghi", "AAA"},
            {"kljf (.+) flskdjflskdjlf", "BBB"}
        };

        foreach(KeyValuePair<string, string> entry in substitutions)
        {
            xml = Regex.Replace(xml, entry.Key, delegate(Match m) { return m.Groups[1].Value; });
            Console.WriteLine(xml);
        }

最后的字符串应该是这样的:

"abc AAA ghi blabla horse 123 jakljd alj ldkfj s;aljf BBB sdlkj flskdjflskdjlf lskjddhcn guffy"

您需要使用lookarounds

"(?<=abc ).+(?= ghi)", "AAA"

这将使您能够替换您want.You不需要捕获组

的词

使用正数loohbehind and lookaheads:

string xml = "abc def ghi blabla horse 123 jakljd alj ldkfj s;aljf kljf sdlkj flskdjflskdjlf lskjddhcn guffy";
Dictionary<string, string> substitutions = new Dictionary<string, string> 
{ 
    {@"(?<=abc\s).+(?=\sghi)", "AAA"},
    {@"(?<=kljf\s).+(?=\sflskdjflskdjlf)", "BBB"}
};

foreach (KeyValuePair<string, string> entry in substitutions)
{
    xml = Regex.Replace(xml, entry.Key, entry.Value);
    Console.WriteLine(xml);
}

它们是零宽度断言,,它们需要满足匹配,但不会包含在结果中。