C#中怎么使用正则表达式

c#
1424
2024/3/25 14:07:57
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中使用正则表达式,可以通过System.Text.RegularExpressions命名空间中的Regex类来实现。以下是一个简单的示例代码:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "Hello, World!";
        string pattern = @"\b\w+\b"; // 匹配单词

        Regex regex = new Regex(pattern);
        MatchCollection matches = regex.Matches(input);

        foreach (Match match in matches)
        {
            Console.WriteLine(match.Value);
        }
    }
}

在上面的示例中,我们使用Regex类来匹配输入字符串中的单词,并将匹配到的单词打印出来。在实际使用时,可以根据需要编写特定的正则表达式模式来匹配不同的字符串模式。

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

推荐阅读: C#中过滤数据时空集合会有什么影响