开发者

Regular expression for 10 digit number without any special characters

开发者 https://www.devze.com 2023-02-04 10:40 出处:网络
What is the regular expression for a 10 digit numeric number (n开发者_StackOverflow中文版o special characters and no decimal).Use this regular expression to match ten digits only:

What is the regular expression for a 10 digit numeric number (n开发者_StackOverflow中文版o special characters and no decimal).


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)"


Use the following pattern.

^\d{10}$


This works for me: only 10 digit number is accepted.

^[0-9]{10}$


\d{10}

I believe that should do it


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.


Use this:

\d{10}

I hope it helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消