Chaka
Chaka

Reputation: 1541

How do I write regex to validate EIN numbers?

I want to validate that a string follows this format (using regex):

valid: 123456789     //9 digits
valid: 12-1234567    // 2 digits + dash + 7 digits

Here's an example, how I would use it:

var r = new Regex("^[1-9]\d?-\d{7}$");
Console.WriteLine(r.IsMatch("1-2-3"));

I have the regex for the format with dash, but can't figure how to include the non-dash format???

Upvotes: 0

Views: 4023

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

^ \d{9} | \d{2} - \d{7} $

Remove the spaces, they are there for readability.

Upvotes: 5

user5315242
user5315242

Reputation:

Regex regex = new Regex("^\\d{2}-?\\d{7}$");

This will accept the two formats you want: 2 digits then an optional dash and 7 numbers.

Upvotes: 6

Related Questions