0

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.

Mr Nobody
  • 359
  • 3
  • 9
  • 23

2 Answers2

2

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})$");
Big Smile
  • 1,103
  • 16
  • 30
1

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})$");
NetMage
  • 26,163
  • 3
  • 34
  • 55
  • Thank you. This seem to work but how can I add an optional space? Allowing the second option to be correct? – Mr Nobody Feb 10 '18 at 00:52
  • @MrNobody Why do you need to do it in a single regex. You can first remove spaces and then use a regex. (in fact, you can do many checks before applying regex) – Eser Feb 10 '18 at 01:04