开发者

Find and replace algorithm

i have some text files that contain

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

How could i replace all above wi开发者_Python百科th the following, since the image width is not static?

<img width="200"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜