使用字典用字符串替换文本

Replacing text with a string using a dictionary

我正在尝试替换与字典中的模式匹配的文本文件中的所有字符串,但我不知道为什么我只替换了最后一个匹配项。

我有一个字典,其中第一个值是模式,第二个是替换值。

谁能帮帮我?

这是 xml 文件的一部分。我正在尝试替换匹配行:

   <book id="bk101">
      <author> ABC</author>
      <title> DEF</title>
      <genre> GHI</genre>
   </book>

这是我到目前为止所做的:

public static void Update()
{
Dictionary<string, string> items = new Dictionary<string,string>();
    items.Add("<book id=\"bk([0-9]{3})\">", "<TEST 01>");
    items.Add("<author>.+</author>", "<TEST 2>");
    items.Add("<genre>.*</genre>", "");
string contentFile;
string replacedContent = null;

try
{
using (StreamReader sr = new StreamReader(@"C:\Users\acrif\Desktop\log\gcf.xml"))
{
    contentFile = sr.ReadToEnd();
    foreach (KeyValuePair<string, string> entry in items)
    {
    replacedContent = Regex.Replace(contentFile, entry.Key, entry.Value);
    }
    if (replacedContent != null)
    {
    WriteLine("Ok.");
    }
}
using (StreamWriter sw = new StreamWriter(@"C:\Users\acrif\Desktop\log\gcf2.xml"))
{
    sw.Write(replacedContent);
}
}
catch (Exception e)
{
}

}

在你的循环中

foreach (KeyValuePair<string, string> entry in items)
{
    replacedContent = Regex.Replace(contentFile, entry.Key, entry.Value);
}

您在每次迭代中将结果分配给 replacedContent。先前存储在 replacedContent 中的替换结果在下一次迭代中被覆盖,因为您没有重用先前的结果。您必须重用在 foreach 循环中存储字符串的变量:

replacedContent = sr.ReadToEnd();
foreach (KeyValuePair<string, string> entry in items)
{
    replacedContent = Regex.Replace(replacedContent, entry.Key, entry.Value);
}