温馨提示×

c# match能否实现多模匹配

c#
小樊
95
2024-07-10 00:50:26
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,Regex类提供了Match方法用于进行正则表达式匹配。Match方法只能返回第一个匹配项,无法实现多模匹配。要实现多模匹配,可以使用Regex.Matches方法,该方法返回所有与正则表达式模式匹配的项的集合。示例如下:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "Hello World! This is a test.";
        string pattern = @"\b\w{5}\b"; // 匹配5个字符的单词

        MatchCollection matches = Regex.Matches(input, pattern);

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

上述代码将输出:

Hello
World
This

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

推荐阅读:c++ string匹配能否实现多模式匹配

0