简体   繁体   中英

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.

如果您还希望此FA45SC有效,请尝试以下操作:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM