前言,想要通过一段代码来实现对文本框中所有手机号码合法性的检测,每个手机号用逗号(,)隔开,除了13*、14*、15*、18*的号外,其余都排除掉。


代码演示:

private void button1_Click(object sender, EventArgs e)
        {
            //这是以13* 14* 15* 18* 开头的号码为准,其余全都不是
            string rightphone = @"^(1(3|4|5|8)[0-9])\d{8}$";
            string oldphone = textBox1.Text.TrimEnd(',');
            //为了防止到最后一次循环length为0
            string exphone = oldphone + ",";
            string newphone = "";
            Regex regex = new Regex(rightphone);
            if (oldphone.IndexOf(',') < 0)
            {
                if (regex.IsMatch(oldphone) == false)
                {
                    textBox1.Text = "";
                }
            }
            else
            {
                for (int i = 0; i < oldphone.Split(',').Length ; i++)
                {
                    if (regex.IsMatch(exphone.Substring(0, exphone.IndexOf(','))) == true)
                    {
                        newphone = newphone + exphone.Substring(0, exphone.IndexOf(',')) + ",";
                    }
                    exphone = exphone.Substring(exphone.IndexOf(',') + 1, exphone.Length - exphone.IndexOf(',') - 1);
                    textBox1.Text = newphone.TrimStart(',').TrimEnd(',');
                }              
            }          
        }