C#正則表達(dá)式和字符串匹配的方法是什么

c#
小億
136
2024-04-28 18:57:42

在C#中,可以使用Regex類來(lái)處理正則表達(dá)式和字符串匹配。以下是一個(gè)簡(jiǎn)單的示例:

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類來(lái)創(chuàng)建一個(gè)正則表達(dá)式對(duì)象,并使用Matches方法來(lái)匹配輸入字符串中符合正則表達(dá)式的部分。最后,我們遍歷MatchCollection對(duì)象,打印出匹配到的結(jié)果。

0