【问题标题】:Find and Replace a section of a string with wildcard type search使用通配符类型搜索查找和替换字符串的一部分
【发布时间】:2011-02-16 07:48:45
【问题描述】:

我希望能够读取文件,并替换以下所有实例:

M9S1800.2 和 S1800(我想摆脱 M9 和 .2)。

我遇到的问题是“S”后面的4位数字每次都可能不同,小数点后的数字也是如此。

例如,

可以是:M9S3200.1 或 M9S5400.1 或 M9S5400.2

有人可以告诉我如何用 C# 做到这一点吗?

我知道如何使用此代码查找和替换:

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。

【问题讨论】:

  • 很高兴您在此处获得有关正则表达式的帮助。这里有一点迂腐的帮助:C# 没有正则表达式,不像 JavaScript。
  • 另外,您应该使用string content = null; using (StreamReader reader = new StreamReadeer(...)) { content = reader.ReadToEnd();}。即使抛出异常也会清理。

标签: c# replace find wildcard


【解决方案1】:
content = Regex.Replace(content, @"M9(S\d{4})\.\d", "$1");

【讨论】:

  • 非常感谢。完美运行。
猜你喜欢
  • 2011-02-17
  • 2016-01-19
  • 2021-11-15
  • 2014-02-11
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2018-12-18
相关资源
最近更新 更多