Rajesh
Rajesh

Reputation: 2502

Regex in c# for allowing numbers and alphabets

I am trying to write a regex that allows different set of inputs.

first 9 characters should be numeric - 123456789

10 character is optional and if present should be Alphabet - 123456789A

11 Character if preset should be aplphanumeric - 123456789AA or 123456789A1

12 - 14 Character if preset should be numeric - 123456789AA123 or 123456789A1123

I tried this but it is not working..

 string sMatch = "^[0-9]{9}([a-zA-Z])\?{1}([0-9A-Za-z])\?{1}([0-9])?{1}([0-9])\?{1}$";
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(sMatch);

Upvotes: 0

Views: 195

Answers (3)

hwnd
hwnd

Reputation: 70722

Try the following

string sMatch = "^(?i)\\b\\d{9}[a-z]?[^\W_]?\\d{0,3}\\b$";

See live demo

Upvotes: 1

IllusiveBrian
IllusiveBrian

Reputation: 3214

A. You need to put an '@' character before the first quotation mark in the string to mark it as a string literal so it handles \? properly.

B. I'd break it up into a few statements, IE:

string preset1 = @"^[0-9]{9}", preset2 = @"[a-zA-Z]{1}", preset3 = @"[0-9A-Za-z]{1}", 
    preset4 = @"[0-9]{3}$";
if (Regex.IsMatch(input, preset1){
    //Do fits first preset
    if (Regex.IsMatch(input, preset1 + preset2){
        //Do fits second preset
        if (Regex.IsMatch(input, preset1 + preset2 + preset3)){
            //Do fits third preset
            if (Regex.IsMatch(input, preset1 + preset2 + preset 3 + preset4)){
                //Do fits fourth preset
            }
        }
    }
}

Upvotes: 0

gwillie
gwillie

Reputation: 1899

i dont know c#'s regex implementation but how about:

\d{9}[a-zA-Z]?[a-zA-Z0-9]?\d{0,3}

Upvotes: 1

Related Questions