用于验证英国国民保险号的正则表达式 [英] Regular Expression to validate UK National Insurance Number

查看:51
本文介绍了用于验证英国国民保险号的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下正则表达式来验证英国国民保险号码

I have the following regular expression which validates the British National Insurance Number

^([a-zA-Z]){2}( )?([0-9]){2}( )?([0-9]){2}( )?([0-9]){2}( )?([a-zA-Z]){1}?$

接受的值为:

AB 12 34 56 A

AB123456A

我也希望接受这个值.谁能帮我解决这个问题?

I want this values also to be accepted. can anyone please help me sort out this?

AB 123456 A

AB 123 456 A

AB 1 2345 6 A

    AB   12   34   56 A    (multiple space anywhere)

即使字符串中有多余的空格或没有空格,RE 也应该可以工作.这可以在 RE 中做到吗?提前致谢.

The RE should work even if there are extra or no spaces in the string. Is this possible to do in RE? Thank you in advance.

推荐答案

编辑:Andrew Bauer 修改了我的答案,添加了对我回答时未知的允许/禁止字符的检查.您应该对他的答案投赞成票,因为它更完整,并且显然可以执行更好的验证.

Edit: Andrew Bauer modified my answer to add checks for allowed/disallowed characters that were unknown at the time I answered. You should up-vote his answer since it is more complete and apparently performs better validation.

如果你不能先删除所有的空格,这应该可行:

If you can't just remove all the whitespace first, this should work:

^\s*[a-zA-Z]{2}(?:\s*\d\s*){6}[a-zA-Z]?\s*$

说明:

^                 # beginning of string
\s*               # optional leading whitespace
[a-zA-Z]{2}       # match two letters
(?:\s*\d\s*){6}   # six digits, with optional whitespace leading/trailing
[a-zA-Z]?         # zero or one letter
\s*               # optional trailing whitespace (just in case)
$                 # end of string

这篇关于用于验证英国国民保险号的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆