Search code examples
c#asp.netregexpostal-code

Convert the given regular expression in veribose format to use a format usable to validate UK postcode in asp.net?


I have regular expression I need to use this regular expression to validate the UK postcode. I have converted that to a format to work with asp.net regular expression engine. Could anyone please guide me what I have done is correct or if there is any mistake in it. Any help will be appreciated.These postcodes returns as validate postcodes W1A 0AX,SO10 9AA, FY9 9AA, WC1A 9AA.

Veribose Format

(GIR\s0AA) |
(
    # A9 or A99 prefix
    ( ([A-PR-UWYZ][0-9][0-9]?) |
         # AA99 prefix with some excluded areas
        (([A-PR-UWYZ][A-HK-Y][0-9](?<!(BR|FY|HA|HD|HG|HR|HS|HX|JE|LD|SM|SR|WC|WN|ZE)[0-9])[0-9]) |
         # AA9 prefix with some excluded areas
         ([A-PR-UWYZ][A-HK-Y](?<!AB|LL|SO)[0-9]) |
         # WC1A prefix
         (WC[0-9][A-Z]) |
         (
            # A9A prefix
           ([A-PR-UWYZ][0-9][A-HJKPSTUW]) |
            # AA9A prefix
           ([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY])
         )
        )
      )
      # 9AA suffix
    \s[0-9][ABD-HJLNP-UW-Z]{2}
    )

format I used to validation postcode as below

return (

    Regex.IsMatch(postcode, "([GIR[ ]0AA])") ||
    Regex.IsMatch(postcode, "(^[A-PR-UWYZ][0-9][0-9]?[ ][0-9][ABD-HJLNP-UW-Z]{2}$)") ||
    Regex.IsMatch(postcode, "(^[A-PR-UWYZ][A-HK-Y][0-9](?<!(BR|FY|HA|HD|HG|HR|HS|HX|JE|LD|SM|SR|WC|WN|ZE)[0-9])[0-9][ ][0-9][ABD-HJLNP-UW-Z]{2}$)") ||
    Regex.IsMatch(postcode, "(^[[A-PR-UWYZ][A-HK-Y](?<!AB|LL|SO)[0-9][ ][0-9][ABD-HJLNP-UW-Z]{2}$)") ||
    Regex.IsMatch(postcode, "(^WC[0-9][A-Z][ ][0-9][ABD-HJLNP-UW-Z]{2}$)") ||
    Regex.IsMatch(postcode, "(^[A-PR-UWYZ][0-9][A-HJKPSTUW][ ][0-9][ABD-HJLNP-UW-Z]{2}$)") ||
    Regex.IsMatch(postcode, "(^[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY][ ][0-9][ABD-HJLNP-UW-Z]{2}$)")

            );
    }

Solution

  • You may use

    (GIR\s0AA)|((([A-PR-UWYZ][0-9][0-9]?)|(([A-PR-UWYZ][A-HK-Y][0-9](?<!(BR|FY|HA|HD|HG|HR|HS|HX|JE|LD|SM|SR|WC|WN|ZE)[0-9])[0-9])|([A-PR-UWYZ][A-HK-Y](?<!AB|LL|SO)[0-9])|(WC[0-9][A-Z])|(([A-PR-UWYZ][0-9][A-HJKPSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))\s[0-9][ABD-HJLNP-UW-Z]{2})
    

    See the regex demo