温馨提示×

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

小亿
182
2023-07-22 13:51:09
栏目: 编程语言

你可以使用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”。

希望对你有所帮助!

0