taj*_*i01 2 .net c# regex methods
我将我的RegularExpression()方法与包含所有if语句的validate()方法分开.如果它像这样分开,我如何使用我的正则表达式代码?我对编程很新,我还在学习如何使用方法请提供一个例子.
public void Validate()
{
RegularExpression();
if (PhoneNumber_Regex.IsMatch(PhonNumb_txBox.Text) == false)
{
MessageBox.Show("Invalid cellphone number");
}
if (Email_Regex.IsMatch(Email_txBox.Text) == false)
{
MessageBox.Show("Invalid E-Mail");
}
}
public RegularExpression(object PhoneNumber_Regex)
{
var PhoneNumber_Regex = new Regex(@"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$");
var Email_Regex = new Regex(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$.");
}
Run Code Online (Sandbox Code Playgroud)
添加一个静态类,您将在其中声明正则表达式:
public static class MyRegexps
{
public static readonly Regex PhoneNumber_Regex = new Regex(@"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$");
public static readonly Regex Email_Regex = new Regex(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$.");
}
Run Code Online (Sandbox Code Playgroud)
然后在调用方法中使用它们:
if (MyRegexps.PhoneNumber_Regex.IsMatch(PhonNumb_txBox.Text) == false)
{
MessageBox.Show("Invalid cellphone number");
}
Run Code Online (Sandbox Code Playgroud)