[英]How to replace only capturing group in Regex.Replace?
我有字典,鍵為模式,替換為值。 每個模式都有一個捕獲組。 我只想用替換項替換捕獲組。 我的嘗試如下,但是當然它正在替換整個模式。 我僅限於.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"
這將使您可以替換所需的單詞。您不需要捕獲組
使用正Loohbehind和前瞻 :
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);
}
它們是零寬度的斷言, 即必須滿足匹配條件,但不會包含在結果中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.