What is proper RegEx expression for SWIFT codes?

abatishchev picture abatishchev · Jun 12, 2010 · Viewed 18k times · Source

I have to filter user input to on my web ASP.NET page:

<asp:TextBox runat="server" ID="recipientBankIDTextBox" MaxLength="11" />
<asp:RegularExpressionValidator runat="server" ValidationExpression="?" ControlToValidate="recipientBankIDTextBox" ErrorMessage="*" />

As far is I know SWIFT code must contain 5 or 6 letters and other symbols up to total length 11 are alphanumeric.

How to implement such rule properly?

Answer

Mark Byers picture Mark Byers · Jun 12, 2010

A swift code should be 8 or 11 letters or digits where the first six must be letters. But anyway it doesn't really matter what it is, what matters is that you understand how to create such an expression. Here is a regular expression with annotations to show you what the parts mean.

^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$
       ^          ^           ^  ^
       |          |           |  |
       6 letters  2 letters   3 letters or digits
                  or digits      |
                                 last three are optional

All the examples on Wikipedia show only upper case letters A-Z. If you also want to allow lowercase letters then change A-Z to A-Za-z. I would check the ISO standard to see what that says, but unfortunately it's not free to obtain a copy.