c#

C#中字符串的正则表达式匹配

小樊
83
2024-08-23 19:00:28
栏目: 编程语言

在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);
        }
    }
}

在上面的示例中,我们定义了一个正则表达式模式\b\w+\b,用于匹配单词。然后使用Regex类创建一个正则表达式对象,调用Matches方法对输入字符串进行匹配,返回所有匹配的结果。最后,我们遍历匹配结果集合,并打印出匹配到的单词。

0
看了该问题的人还看了