查找并用通配符类型搜索替换字符串的一部分 [英] Find and Replace a section of a string with wildcard type search
问题描述
我希望能够读取文件,并替换以下所有实例:
I want to be able to read a file, and replace all instances of:
带有S1800的M9S1800.2(我想摆脱M9和.2).
M9S1800.2 with S1800 (I want to get rid of the M9 and the .2).
我遇到的问题是,"S"后面的4位数字以及小数点后的数字每次都可能不同.
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.
例如,
可以是:M9S3200.1或M9S5400.1或M9S5400.2
It can be: M9S3200.1 or M9S5400.1 or M9S5400.2
有人可以告诉我如何使用C#吗?
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");
但是对于M9S3200.1,我想执行通配符类型替换.例如,将M9S * .1替换为S *,这样M9S3200.1就会变成S3200.
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.
推荐答案
content = Regex.Replace(content, @"M9(S\d{4})\.\d", "$1");
这篇关于查找并用通配符类型搜索替换字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!