How can I replace multiple texts using Replace?

1

I'm looking to replace several strings and then write them to a .csv file

Everything works well when I replace a single text, but when wanting to replace 2 or more, I only take the last replacement text, which only allows me to put a string after WriteAllText .

This is my code:

string reemplazo = "";
string reemplazo2 = "";

string Arch = File.ReadAllText(originalFileName); //Aqui leo mi archivo .csv
reemplazo = Regex.Replace(Arch, @"/", @"/");
reemplazo2 = Regex.Replace(Arch, @"–", @"-");

File.WriteAllText(newFileName.Substring(0, newFileName.Length - 4) + "Test.csv", reemplazo); //solo puedo poner un valor del remplazo

File.Move(originalFileName, newFileName);

files.Add(newFileName);
    
asked by A arancibia 05.06.2018 в 20:18
source

1 answer

2

OK .. you have a quite simple problem, and that is that you are not replacing the text on the string that you just used, if not always on the original, for which, the text that remains is only that of the last replacement.

//Obtenemos todo el string
string Arch = File.ReadAllText(originalFileName); //Aqui leo mi archivo .csv
//reemplazamos sobre Arch
reemplazo = Regex.Replace(Arch, @"/", @"/");
//reemplazamos sobre Arch, otra vez :(
reemplazo2 = Regex.Replace(Arch, @"–", @"-");

Actually, replacement2 should be:

//tenemos que reemplazar, sobre reemplazo!!!!!
reemplazo2 = Regex.Replace(reemplazo , @"–", @"-");

Replace replaces in a string, and returns another different string with the replacements made. therefore, the next replace, you must if or if you use that new string.

As a note, you could do replace and send the content to the same string without problems:

//Esto es valido tambien!
string Arch = File.ReadAllText(originalFileName); //Aqui leo mi archivo .csv
Arch = Regex.Replace(Arch, @"/", @"/");
Arch = Regex.Replace(Arch, @"–", @"-");
    
answered by 05.06.2018 / 20:22
source