Find and Replace a section of a string with wildcard type search

岁酱吖の 提交于 2020-01-15 12:47:09

问题


I want to be able to read a file, and replace all instances of:

M9S1800.2 with S1800 (I want to get rid of the M9 and the .2).

The problem I am having is that the 4 digit number after the "S" can be different every time, as well as the number after the decimal.

For example,

It can be: M9S3200.1 or M9S5400.1 or M9S5400.2

Can someone please show me how to do this with C#?

I know how to find and replace by using this code:

StreamReader reader = new StreamReader(fDialog.FileName.ToString());
string content = reader.ReadToEnd();
reader.Close();

content = Regex.Replace(content, "M2", "M3");

but with the M9S3200.1, I want to do a wildcard type replace. For example it would be like replace M9S*.1 with S* so M9S3200.1 would just become S3200.


回答1:


content = Regex.Replace(content, @"M9(S\d{4})\.\d", "$1");


来源:https://stackoverflow.com/questions/2780023/find-and-replace-a-section-of-a-string-with-wildcard-type-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!