【问题标题】:Replacing text with a string using a dictionary使用字典用字符串替换文本
【发布时间】:2018-04-29 16:37:18
【问题描述】:

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

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

谁能帮帮我?

这是 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)
{
}

}

【问题讨论】:

  • 您不使用 XDocument 类的任何具体原因? (或 XmlDocument 或 XmlReader/XmlWriter)
  • 其实不是。我要检查 XmlDocument 和 XmlReader/XmlWriter。谢谢。

标签: c# string-parsing


【解决方案1】:

在你的循环中

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 2020-10-08
    相关资源
    最近更新 更多