c#中怎么用regex匹配多个字符串

c#
611
2024/2/19 15:11:35
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,可以使用Regex类来匹配多个字符串。下面是一个示例代码:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "Hello world! This is a test.";
        string[] keywords = { "Hello", "world", "test" };

        foreach (string keyword in keywords)
        {
            // 使用Regex类的静态方法Match来进行匹配
            Match match = Regex.Match(input, keyword);

            if (match.Success)
            {
                Console.WriteLine("Found '{0}' at position {1}.", keyword, match.Index);
            }
            else
            {
                Console.WriteLine("'{0}' not found.", keyword);
            }
        }
    }
}

输出结果将会是:

Found 'Hello' at position 0.
Found 'world' at position 6.
Found 'test' at position 21.

在上面的示例中,我们定义了一个字符串数组keywords,并通过循环,使用Regex.Match方法来在输入字符串input中逐个匹配关键字。如果找到了匹配项,就会输出关键字的位置;否则,输出not found

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

推荐阅读: c# nameof如何避免拼写错误