正则表达式可以让你(相对)轻松地确定字符串是否与某种模式匹配。此示例展示了如何在 C# 中创建字符串扩展方法来确定字符串是否与正则表达式匹配
下面的StringExtensions类定义了Matches字符串扩展方法。
public static class StringExtensions
{
// Extension to add a Matches method to the string class.
public static bool Matches(this string the_string,
string pattern)
{
Regex reg_exp = new Regex(pattern);
return reg_exp.IsMatch(the_string);
}
}
该扩展方法创建一个Regex对象并使用其IsMatch方法来确定字符串是否与表达式匹配。
主程序使用扩展方法如下面的代码所示。