利用正则表达式验证手机或电话号码

privatevoid btnTest_Click(object sender, EventArgs e)
        
{
            
//using System.Text.RegularExpressions; 先using这一段

            
string _Result= "";
            
string _Pattern= @"(?:13\d|15[89])-?\d{5}(\d{3}|\*{3})";
             Match m
= Regex.Match(txtMobile.Text, _Pattern);           

            
if (m.Groups.Count> 1)//表示能匹配到有效的手机号码 比如为:13016752109 不包含区号 
          {
                 _Result
= m.Groups[0].Value;
             }

            
else
           
{
                 _Pattern
= @"(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,5}))?";
                 m
= Regex.Match(txtMobile.Text, _Pattern);
                
if (m.Groups.Count> 1)//表示能匹配到有效电话号码 有效格式为:区号(2-3位)-电话号码(7-8位)-分机号(3-5位) 分机号可选
              {
                     _Result
= m.Groups[0].Value;
                 }

             }


            
if (_Result!= "")
          
{
                 MessageBox.Show(
"有效的电话/手机号为:"+ _Result);
             }

            
else
          
{
                 MessageBox.Show(
"无效的电话/手机号码,请重新输入");
             }

           
         }

你可能感兴趣的:(C#WinForm)