Regular expression for 10 digit number without any special characters

前端 未结 5 726
轻奢々
轻奢々 2020-12-06 03:44

What is the regular expression for a 10 digit numeric number (no special characters and no decimal).

相关标签:
5条回答
  • 2020-12-06 04:24

    Use this regular expression to match ten digits only:

    @"^\d{10}$"
    

    To find a sequence of ten consecutive digits anywhere in a string, use:

    @"\d{10}"
    

    Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits and not more you can use negative lookarounds:

    @"(?<!\d)\d{10}(?!\d)"
    
    0 讨论(0)
  • 2020-12-06 04:32

    An example of how to implement it:

    public bool ValidateSocialSecNumber(string socialSecNumber)
    {
        //Accepts only 10 digits, no more no less. (Like Mike's answer)
        Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)");
    
        if(pattern.isMatch(socialSecNumber))
        {
            //Do something
            return true;
        }
        else
        {
            return false;
        }
    }
    

    You could've also done it in another way by e.g. using Match and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.

    0 讨论(0)
  • 2020-12-06 04:33

    Use the following pattern.

    ^\d{10}$
    
    0 讨论(0)
  • 2020-12-06 04:44

    Use this:

    \d{10}
    

    I hope it helps.

    0 讨论(0)
  • 2020-12-06 04:50
    \d{10}
    

    I believe that should do it

    0 讨论(0)
提交回复
热议问题