Regex for a New Zealand Bank Account

Henry Aung / 2 years ago

According to the Wikipedia article:

Account numbers are generally presented in the format:

BB-bbbb-AAAAAAA-SSS

where B is the bank number (2 digits), b is the branch number (4 digits), A is the account number (7 digits) and S are digits of the suffix (2 or 3 digits). Where a bank displays the suffix as two digits, a leading zero is added to pad the suffix to three digits; i.e. BBbbbb-AAAAAAA-SS becomes BBbbbb-AAAAAAA-0SS.

The above specification would translate to the following regex code for C#:

const string regex = @"^\d{2}\-\d{4}\-\d{7}\-(\d{3}|\d{2})$";

That would cover following test-cases:

[Theory]
[InlineData("03-0658-1234567-03", true)]
[InlineData("03-0658-1234567-003", true)]
[InlineData("ab-1111-1234567-1fd", false)]
[InlineData("ab03-0658-1234567-03ghj", false)]
[InlineData("030658123456703--", false)]
[InlineData("--030658123456703", false)]
[InlineData("030658123456703abc", false)]
[InlineData("030abc123456703", false)]
[InlineData("03--0658-1234567-03", false)]
[InlineData("03 0658 1234567 03", false)]
[InlineData("0-01111-1234567-123", false)]
public void CanValidate(string given, bool expected)
{
    // When
    var actual  = Validate(given);

    // Then
    Assert.True(expected, actual, $"Given: {given}");
}

;

Filed under: