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

avatar
作者
筋斗云
阅读量:0

在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方法来找到输入字符串中所有匹配的内容。最后,我们遍历匹配集合并打印出匹配的结果。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!