C# 使用正则表达式替换字符串

C# 中使用正则表达式替换字符串可以使用 Regex 类的 Replace 方法。方法定义如下:

public static string Replace(string input, string pattern, string replacement);

其中,input 表示要进行替换的字符串,pattern 表示要匹配的正则表达式模式,replacement 表示要替换成的字符串。

例如,假设要把一个字符串中所有的数字替换为”#”,可以使用以下代码:

string input = "1234567890";
string pattern = @"d";
string replacement = "#";
string result = Regex.Replace(input, pattern, replacement);

其中,正则表达式模式 @”d” 表示匹配任意一个数字字符。执行完以上代码后,result 的值应该是”##########”。