Regular expression for 10 digit number without any special characters

C#.NetRegex

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Use the following pattern.

^\d{10}$

Solution 3 - C#

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

^[0-9]{10}$

Solution 4 - C#

\d{10}

I believe that should do it

Solution 5 - C#

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.

Solution 6 - C#

Use this:

\d{10}

I hope it helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGrasshopperView Question on Stackoverflow
Solution 1 - C#Mark ByersView Answer on Stackoverflow
Solution 2 - C#A_NabelsiView Answer on Stackoverflow
Solution 3 - C#Soraya AnvariView Answer on Stackoverflow
Solution 4 - C#m.edmondsonView Answer on Stackoverflow
Solution 5 - C#Force444View Answer on Stackoverflow
Solution 6 - C#dzendrasView Answer on Stackoverflow