使用 C# 正则表达式删除空格
csharpprogrammingserver side programming更新于 2025/9/1 0:52:17
假设我们要从以下字符串 str1 中删除空格。
string str1 = "Brad Pitt";
现在,使用正则表达式替换将空格替换为空。这里我们使用了 System.Text.RegularExpressions。
string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");
让我们看一下完整的例子。
示例
using System;
using System.Text.RegularExpressions;
namespace Demo {
class Program {
static void Main(string[] args) {
string str1 = "Brad Pitt";
Console.WriteLine(str1);
string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");
Console.WriteLine(str2);
}
}
}
输出
Brad Pitt BradPitt

