Gavin
Gavin

Reputation: 1233

Regex Help: One charecter, followed by at least one digit

I require a regex that will text that a string starts with one chaecter (a-z) and is followed by at least one digit.

I have tried...

^[a-zA-Z]{1}\d+

my test data is...

a1234 (pass)
B123444434 (pass)
Z098745 (pass)
ZZ12345 (fail)
G4b553b3 (fail)

The problem is that the last two lines shoudl fail but dont, Im not sure if the problem is my regex or my c# (below);

    int pass = 0;
    int fail = 0;

    string[] testdata = 
    {
        "a1234", 
        "B1234", 
        "Z098745", 
        "ZZ12345", 
        "G4b5533", 
    };

    string sPattern = "[a-zA-Z]{1}\\d+";

    foreach (string s in testdata)
    {
        if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern))
        {
            pass++;
        }
        else
        {
            fail++;
        }
    }

Upvotes: 0

Views: 188

Answers (2)

Gavin
Gavin

Reputation: 1233

After a rethink (and a good nights sleep), I have come up with this...

^[A-Za-z]{1}\d+.$*[0-9]$

• Must start with a character a-z (not case sensitive)

• First character must be followed by at least one numerical digit

• Last character must be a numerical digit (to prevent "A1234A" or "A1A" matching)

Thanks for all the help Vladimir and jornak.

Upvotes: -1

Vladimir
Vladimir

Reputation: 9743

You seem to have missed ^ in your code, so Z12345 matches for ZZ12345 and b5533 matches for G4b5533.

And as it was mentioned, {1} is redundant.

I believe you should have

string sPattern = "^[a-zA-Z]\\d+$";

in your code.

Upvotes: 4

Related Questions