c#

c# match能否实现多模匹配

小樊
85
2024-07-10 00:50:26
栏目: 编程语言

在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

0
看了该问题的人还看了