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}?$
Accepted values are:
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)
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.
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*$
Explanation:
^ # 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