怎么使用c#正则表达式去掉标点符号

733
2023/8/2 13:51:09
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

你可以使用System.Text.RegularExpressions.Regex类来实现这个需求。下面是一个示例代码,演示如何使用C#正则表达式去掉标点符号:

using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "Hello, World! This is a sentence.";
// 定义正则表达式模式,匹配标点符号
string pattern = @"[\p{P}-[.]]+";
// 使用正则表达式替换标点符号为空字符串
string result = Regex.Replace(input, pattern, "");
Console.WriteLine(result);
}
}

在上面的代码中,我们定义了一个正则表达式模式[\p{P}-[.]]+,它匹配所有的标点符号(除了句号)。然后,我们使用Regex.Replace方法将匹配到的标点符号替换为空字符串,从而去掉它们。输出结果为:“Hello World This is a sentence”。

希望对你有所帮助!

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 在C#开发中怎样降低SQL注入的风险