Mr Nobody
Mr Nobody

Reputation: 389

C# - UK Postcode Regex Expression not working as expected?

I looked at many questions on this website such as this one for Regex Expression to validate UK Postcodes:

I have the following examples:

I have the following code:

static void Main(string[] args)
{
    string[] postcodes = { "FA4 5SC", "FA45SC",
                      "1FA4 5SC"};    
    Regex rgx = new Regex("^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$");

    foreach (string postcode in postcodes)
        Console.WriteLine("{0} {1} a valid postcode number.",
                          postcode,
                          rgx.IsMatch(postcode) ? "is" : "is not");     
    Console.ReadKey();
}

I get the following output:

FA4 5SC is a valid postcode number.
FA45SC is not a valid postcode number.
1FA4 5SC is a valid postcode number.

What do I need to amend in my regex so it invalidates the last two postcodes. Meaning if a postcode starts with a number it should be invalid.

Upvotes: 0

Views: 1448

Answers (2)

NetMage
NetMage

Reputation: 26917

I believe the regular expression has a precedence error - the alternation after the first parentheses group has lower precedence than the caret, so it only tests if it find that group at the beginning of the string. Also, it has a lot of unneeded parenthesis for the alternation options otherwise, which makes it pretty hard to follow.

Try this:

Regex rgx = new Regex("^([Gg][Ii][Rr] 0[Aa]{2}|([A-Za-z][0-9]{1,2}|[A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2}|[A-Za-z][0-9][A-Za-z]|[A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]) [0-9][A-Za-z]{2})$");

To make the space optional,

Regex rgx = new Regex("^([Gg][Ii][Rr] 0[Aa]{2}|([A-Za-z][0-9]{1,2}|[A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2}|[A-Za-z][0-9][A-Za-z]|[A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]) ?[0-9][A-Za-z]{2})$");

Upvotes: 1

Big Smile
Big Smile

Reputation: 1124

Try this if you also want this FA45SC to be valid:

Regex rgx = new Regex("^([Gg][Ii][Rr] 0[Aa]{2}|([A-Za-z][0-9]{1,2}|[A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2}|[A-Za-z][0-9][A-Za-z]|[A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]) {0,1}[0-9][A-Za-z]{2})$");

Upvotes: 2

Related Questions