代码之家  ›  专栏  ›  技术社区  ›  Pablo

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

  •  1
  • Pablo  · 技术社区  · 9 年前

    我有一个字典,关键字作为模式,替换值作为值。每个模式都有一个捕获组。我想用替换替换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 回复  |  直到 9 年前
        1
  •  1
  •   vks    9 年前

    你需要使用 lookarounds .

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

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

        2
  •  0
  •   Saeb Amini    9 年前

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

    它们是零宽度断言, ,他们必须满足比赛要求,但不包括在结果中。