Javascript英国邮政编码正则表达式 [英] Javascript UK postcode regex
问题描述
我有一个javascript正则表达式验证英国邮政编码。它运作良好,但它没有考虑到有些人在中间用空格写它而其他人没有。我试图添加这个但不能解决这个问题:S英国邮政编码主要是2个字母后跟1或2个数字,可选的空格和& 1个数字和2个字母。
I have a javascript regex which validates UK postcodes. It works well, but it doesn't take into account that some people write it with spaces in the middle and others don't. I've tried to add this but cant work it out :S UK postcodes are mainly 2 letters followed by 1 or 2 numbers, optional whitespace & 1 number and 2 letters.
这是我的正则表达式,用于验证没有空格的邮政编码:
Here is my regex which validates postcodes without spaces:
[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
任何想法?
修改
我改变了正则表达式,因为我意识到一个组缺少小写字符。
I changed the regex as I realised one group was missing lowercase chars.
推荐答案
另一种选择解决方案是从字符串中删除所有空格,然后通过您已有的正则表达式运行它:
An alternative solution would be to remove all spaces from the string, then run it through the regular expression that you already have:
var postalCode = '…';
postalCode = postalCode.replace(/\s/g, ''); // remove all whitespace
yourRegex.test(postalCode); // `true` or `false`
这篇关于Javascript英国邮政编码正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!