加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 电话号码验证

发布时间:2020-12-15 23:45:58 所属栏目:百科 来源:网络整理
导读:我有这个代码来验证电话号码,但它看起来有点尴尬.我猜这是一个更好的方法来解决这个问题.我怎样才能提高效率呢? public static bool validTelephoneNo(string telNo){ bool condition = false; while (condition == false) { Console.WriteLine("Enter a ph
我有这个代码来验证电话号码,但它看起来有点尴尬.我猜这是一个更好的方法来解决这个问题.我怎样才能提高效率呢?

public static bool validTelephoneNo(string telNo)
{
    bool condition = false;
    while (condition == false)
    {
        Console.WriteLine("Enter a phone number.");
        telNo = Console.ReadLine();
        if (telNo.Length > 8)
        {
            if (telNo.StartsWith("+") == true)
            {
                char[] arr = telNo.ToCharArray();
                for (int a = 1; a < telNo.Length; a++)
                {
                    int temp;

                    try
                    {
                        temp = arr[a];
                    }

                    catch
                    {
                        break;
                    }

                    if (a == telNo.Length - 1)
                    {
                        condition = true;
                    }
                }
            }
        }
    }
    return true;
}

解决方法

使用正则表达式可以轻松实现目标:

public static bool validTelephoneNo(string telNo)
{
    return Regex.Match(telNo,@"^+d{1,7}$").Success;
}

这个模式完全如上所述:由整数组成,长度小于8位,并且在开始时有一个加号,如果条件某种程度上更复杂,也可以修改此模式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读