views:

37

answers:

1

Hello, i have some text files that contain

<img width="100" or <img width="1400" or....

How could i replace all above with the following, since the image width is not static?

<img width="200"
+1  A: 

For a regular expression based solution you could use this:

string path = "input.html";
string s = File.ReadAllText(path);
s = Regex.Replace(s, @"<img width=""\d+""", @"<img width=""200""");
File.WriteAllText(path, s);

It will work if your files are from a trusted source in a format that you control. If not and this is HTML, you might want to look at a HTML parser such as HTML Agility Pack.

If the files are too large to read into memory you might want to handle the file one line at a time.

It can also sometimes be a good idea to write to a temporary file and only delete the original file once you are sure that the write has succeeded.

Mark Byers
+1 for mentioning HTML Agility Pack
modosansreves