温馨提示×

c# match如何在字符串中使用

c#
小樊
91
2024-07-10 00:41:24
栏目: 编程语言

在C#中,您可以使用Regex类来进行字符串匹配操作。下面是一个简单的示例,演示如何使用Regex类来在字符串中查找匹配的内容:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "Hello, my email address is test@test.com";
        string pattern = @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b";
        
        Regex regex = new Regex(pattern);
        MatchCollection matches = regex.Matches(input);
        
        foreach (Match match in matches)
        {
            Console.WriteLine(match.Value);
        }
    }
}

在上面的示例中,我们首先定义了一个要匹配的字符串input和一个正则表达式模式pattern,该模式用于匹配电子邮件地址。然后我们使用Regex类创建了一个正则表达式对象regex,并调用它的Matches方法来找到输入字符串中所有匹配的内容。最后,我们遍历匹配集合并打印出匹配的结果。

0