我有一个javascript regex,它验证英国的邮政编码。它工作得很好,但它并没有考虑到,有些人用中间的空格写,而另一些人则没有。我试着把它加进去,但找不出:英国的邮政编码主要是两个字母,后面跟着一个或两个数字,可选的空格&一个数字和两个字母。
下面是我的regex,它验证没有空格的邮政编码:
[A-PR-UWYZa-pr-uwyz0-9][A-HK-Ya-hk-y0-9][AEHMNPRTVXYaehmnprtvxy0-9]?[ABEHMNPRVWXYabehmnprvwxy0-9]?{1,2}[0-9][ABD-HJLN-UW-Zabd-hjln-uw-z]{2}|(GIRgir){3} 0(Aa){2})$/g有什么想法吗?
编辑
当我意识到一个组缺少小写字符时,我改变了regex。
发布于 2012-06-18 11:56:08
另一种解决方案是从字符串中删除所有空格,然后通过您已经拥有的正则表达式运行它:
var postalCode = '…';
postalCode = postalCode.replace(/\s/g, ''); // remove all whitespace
yourRegex.test(postalCode); // `true` or `false`发布于 2012-06-18 11:51:59
两个字母,后面跟着一个或两个数字,可选的空格&一个数字和两个字母。
示例:
/^[a-z]{2}\d{1,2}\s*\d[a-z]{2}$/i用http://www.myregextester.com/解释
^ the beginning of the string
----------------------------------------------------------------------
[a-z]{2} any character of: 'a' to 'z' (2 times)
----------------------------------------------------------------------
\d{1,2} digits (0-9) (between 1 and 2 times
(matching the most amount possible))
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
\d digits (0-9)
----------------------------------------------------------------------
[a-z]{2} any character of: 'a' to 'z' (2 times)
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string发布于 2013-06-04 09:42:02
我们发现大多数regex没有完全覆盖英国的邮政编码。我们发现它需要涵盖以下几种选择:
基于此,我建议:
/^([A-Z][A-Z0-9]?[A-Z0-9]?[A-Z0-9]? {1,2}[0-9][A-Z0-9]{2})$/;
GIR0AA邮政编码过去属于Girobank,但不再受支持,请参阅参考资料:王国
https://stackoverflow.com/questions/11081786
复制相似问题