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

时间:2015-09-03 09:34:52

标签: c# regex replace .net-3.5

我有字典,键作为模式,替换为值。每个模式都有一个捕获组。我想替换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"

2 个答案:

答案 0 :(得分:1)

您需要使用lookarounds

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

这将使您能够替换所需的单词。您不需要捕获组

答案 1 :(得分:0)

使用正面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);
}

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