如何在Regex.Replace中替换仅捕获组
本文关键字:替换 Regex Replace | 更新日期: 2023-09-27 18:10:55
我有一个字典,键作为模式,替换为值。每个模式有一个捕获组。我想替换只有捕获组与替换。我的尝试如下,但它当然是替换整个模式。我仅限于。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"
这将使您能够替换您想要的单词。你不需要capture group
使用正面向后看和正面看:
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);
}
它们是零宽度断言,即。