简体   繁体   English

C#-英国邮政编码正则表达式无法正常工作?

[英]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] FA4 5SC [有效]

  • FA45SC [Valid] FA45SC [有效]

  • 1FA4 5SC [Invalid] 1FA4 5SC [无效]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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