如何在C#中使用正则表达式?

在C#中,System. Text. Regular Expressions提供了正则表达式的所有相关操作。

 

在C#中,正则表达式的所有元字符可以在这里获取到。

 

以下是一个通用的正则表达式的代码:

 

string s1 = “asdfasdgasgfasdfasdfsad”;

string spattern = “as”;

//是否匹配成功
if( Regex.IsMatch(s1, spattern))
{
//获取所有匹配项
MatchCollection mcs = Regex.Matches(s1, spattern);

foreach (Match mc in mcs)
{
//获取所有匹配子集,其中第一个子集为完整匹配项,第二个子集为()项
GroupCollection gcs = mc.Groups;

Console.WriteLine(gcs[0].Value);
}
}
Console.ReadKey();

}

与VBA不一样的是,C#中正则中匹配到的Groups集合,第一个元素是完整的匹配字符串,第二个元素开始才是括号里面匹配到的字符串。

       

发表评论