Phi*_*ung 4 javascript regex postal-code
我有一个javascript正则表达式验证英国邮政编码.它运作良好,但它没有考虑到有些人在中间用空格写它而其他人没有.我试图添加这个,但不能解决它:S英国邮政编码主要是2个字母后跟1或2个数字,可选的空格和1个数字和2个字母.
这是我的正则表达式,它验证没有空格的邮政编码:
[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
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
编辑
我改变了正则表达式,因为我意识到一个组缺少小写字符.
2个字母后跟1或2个数字,可选的空格和1个数字和2个字母.
例:
/^[a-z]{2}\d{1,2}\s*\d[a-z]{2}$/i
Run Code Online (Sandbox Code Playgroud)
用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
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是从字符串中删除所有空格,然后通过您已有的正则表达式运行它:
var postalCode = '…';
postalCode = postalCode.replace(/\s/g, ''); // remove all whitespace
yourRegex.test(postalCode); // `true` or `false`
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10059 次 |
| 最近记录: |