Search code examples
c#regexpostal-code

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:

  • FA4 5SC [Valid]

  • FA45SC [Valid]

  • 1FA4 5SC [Invalid]

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.


Solution

  • 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})$");