温馨提示×

C#正则表达式和字符串匹配的方法是什么

c#
小亿
88
2024-04-28 18:57:42
栏目: 编程语言

在C#中,可以使用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类来创建一个正则表达式对象,并使用Matches方法来匹配输入字符串中符合正则表达式的部分。最后,我们遍历MatchCollection对象,打印出匹配到的结果。

0