Nick
Nick

Reputation: 23

Using .NET Regular Expression, match any string with exactly 9 digits

I'm trying to create a regex expression to match any string that has exactly 9 digits. the digits can exist anywhere in the string.

For example, if you passed in the following strings, you'd get a match: 123456789 123aeiou456abc789

These strings would fail to provide a match 12345678 1234567890

Upvotes: 2

Views: 1688

Answers (3)

Mark Byers
Mark Byers

Reputation: 838096

Try this:

@"^(\D*\d){9}\D*$"

Or use this improved version. It assumes that you only want to match 0-9 and not other characters that represent digits in other languages. It also uses a non-capturing group to improve performance:

"^(?:[^0-9]*[0-9]){9}[^0-9]*$"

Here's a breakdown of what it means:

^        Start of string.
(?:      Start a non-capturing group.
[^0-9]*  Match zero or more non-digits.
[0-9]    Match exactly one digit.
)        Close the group.
{9}      Repeat the group exactly 9 times.
[^0-9]*  Match zero or more non-digits.
$        End of string.

Here's a testbed for it:

string regex = "^(?:[^0-9]*[0-9]){9}[^0-9]*$"
string[] tests = {
                     "123456789",
                     "123aeiou456abc789",
                     "12345678",
                     "1234567890"
                 };
foreach (string test in tests)
{
    bool isMatch = Regex.IsMatch(test, regex); 
    Console.WriteLine("{0}: {1}", test, isMatch);
}

Results:

123456789: True
123aeiou456abc789: True
12345678: False
1234567890: False

Upvotes: 9

VoodooChild
VoodooChild

Reputation: 9784

check out the website

http://www.regexlib.com/CheatSheet.aspx

I found it tobe very helpful.

Upvotes: 1

eidylon
eidylon

Reputation: 7238

Here's my take: ^[^0-9]*[0-9]{9}[^0-9]*$

FWIW, there is a REALLY cool little app to help you build RegEx's which will parse them and explain what your expression is doing in plain English as well as providing an actual UI to help you add expressions you may not be very familiar with. Check out Expresso.

Upvotes: 0

Related Questions