C# Replace parts of String in txt file

Asked

Viewed 148 times

0

Hello.

I’m studying C# and I’m struggling with a function.

I have an array, like below, where each node contains an id, a Pattern(regex) and a value for replacing the part of the string that matches that value.

I load the contents of the txt file into contenFile and if, for example, you match some part of the contenFile, you replace the match with "ABC" and so with the other positions of the array. If no match, enter the value at the end.

The file contains fields to match and not match

< tag 101" > < tag2 >BBBBBBBBBBB< /tag2 > < tag4 >CCCCCC< /tag4 > < tag 101" >

If anyone can help or indicate any content for study, please.

At the moment the code is like this:

public void Edit()
{
string[,] items = {{"001", "<tag ([0-9]{3})\">", "ABC"},
                    {"002", "<tag2>.+</tag2>", "DEF"},
                    {"", "<tag3>.+</tag3>", "GHI"}};
try
{
using (StreamReader sr = new StreamReader(@"C:\test.xml"))
{
string contentFile = sr.ReadToEnd();

foreach (string entry in items)
{
if (!Regex.IsMatch(contentFile, entry[1].ToString()))
{
contentFile = contentFile.Insert(contentFile.Length, entry[2].ToString());
}
else
{
contentFile = Regex.Replace(contentFile, entry[1].ToString(), entry[2].ToString());
}
}
}
}
catch (Exception ex)
{
}
}
  • 1

    And what is he capturing? What do you want to capture?

  • The idea is to create a new file with the edited data (I haven’t done yet pq this part doesn’t work). However, I cannot set the new values in contentFile to then write to the file. The data loaded from the original file remains.

  • Why don’t you use an XML interpreter and change the tag names next?

  • The Exercise should be done with a hehehe text file. I put the xml structure by msm aesthetics, but I must manipulate it like a txt.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.