Nil Pun
Nil Pun

Reputation: 17373

Regular expression for 6 or 8 digits

Could anyone please help with C# regular expression for requirement below, please?

  1. should start with 1 and should be 6 digit long.
  2. should start with 7 and should be 6 digit long.
  3. should be 8 digit long.

Update: Apologies not clarifying the requirement. They are individual cases ie. all I need is a regular expression to these specific cases (i.e. 3 in total).

Upvotes: 3

Views: 5423

Answers (2)

Joe
Joe

Reputation: 82584

Not a regular expression, and now verifies a proper integer and save it into output:

string digits = ...
bool valid;
char firstChar;
int output;

switch(digits.Length) 
{
    case 6:
        firstChar = digits[0];
        valid = firstChar == '1' || firstChar == '7';
        break;
    case 8:
        valid = true;
        break;
    default:
        valid = false;
        break;
}

if (valid && int.TryParse(digits, out output))  
{
    ...
}

Upvotes: 5

zerkms
zerkms

Reputation: 254906

Here it is:

^((1|7)\d{5}|\d{8})$

or following NullUserException ఠ_ఠ advice:

^([17]\d{5}|\d{8})$

Upvotes: 10

Related Questions