Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match Australian Business Number (ABN)

Tags:

regex

I need a regex to match a value in which each character can be a digit from 0 to 9 or a space. The value must contain exactly 11 digits.

For example, it should match values in the format '012 345 678 90' or '01234567890'.

Can anyone please help me on this?

like image 462
Mahesh Avatar asked Nov 27 '22 05:11

Mahesh


1 Answers

For the sake of other Aussie developers out there who may find this in the future:

^(\d *?){11}$

Matches 11 digits with zero or more spaces after each digit.

Edit:

As @ElliottFrisch mentioned, ABNs also have a mathematical formula for proper validation. It would be very difficult (or impossible) to use regex to properly validate an ABN - although the above regex would at least match 11 digit numbers with spacing. If you're after actual validation, perhaps regex isn't the tool for you in this case.

Further reading:

https://abr.business.gov.au/Help/AbnFormat

Here's a PHP implementation:

http://www.clearwater.com.au/code

Code copied from the above page in case it becomes unavailable someday:

//   ValidateABN
//     Checks ABN for validity using the published 
//     ABN checksum algorithm.
//
//     Returns: true if the ABN is valid, false otherwise.
//      Source: http://www.clearwater.com.au/code
//      Author: Guy Carpenter
//     License: The author claims no rights to this code.  
//              Use it as you wish.

function ValidateABN($abn)
{
    $weights = array(10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19);

    // strip anything other than digits
    $abn = preg_replace("/[^\d]/","",$abn);

    // check length is 11 digits
    if (strlen($abn)==11) {
        // apply ato check method 
        $sum = 0;
        foreach ($weights as $position=>$weight) {
            $digit = $abn[$position] - ($position ? 0 : 1);
            $sum += $weight * $digit;
        }
        return ($sum % 89)==0;
    } 
    return false;
}

And a javascript one which I found here:

http://www.mathgen.ch/codes/abn.html

like image 98
Iain Fraser Avatar answered Nov 30 '22 22:11

Iain Fraser