Reputation: 21
I'm trying to replace all strings in a text file that matches with a pattern in a dictionary, but I don't know why I'm only getting last match replaced.
I have a dictionary where the first value is the pattern and the second is the replacing value.
Can anyone help me?
This is part of the xml file. I'm trying to replace matching lines:
<book id="bk101">
<author> ABC</author>
<title> DEF</title>
<genre> GHI</genre>
</book>
this is what I did until now:
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)
{
}
}
Upvotes: 0
Views: 1187
Reputation: 13674
In your loop
foreach (KeyValuePair<string, string> entry in items)
{
replacedContent = Regex.Replace(contentFile, entry.Key, entry.Value);
}
you are assigning the result to replacedContent
in each iteration. The replacement result that was previously stored in replacedContent
is overwritten in the next iteration, since you are not reusing the previous result. You have to reuse the variable that stores the string in the foreach
loop:
replacedContent = sr.ReadToEnd();
foreach (KeyValuePair<string, string> entry in items)
{
replacedContent = Regex.Replace(replacedContent, entry.Key, entry.Value);
}
Upvotes: 1