Search code examples
pythonregexstringnumbers

python: regex match credit card starting with fixed letters


I want to write a regex that matches the following credit card that starts with fixed letters, e.g,

examples = ['AU01 0000 1234 5678 9012 00', 'AU01 3200 1564 5678 9987 55']

I have written the following regex but it does not capture the letters 'AU'.

regex = r'(?:(\w*AU)[0-9]{4}\s){3}[0-9]{4}|[0-9]{16}|[0-9]{2}'

Solution

  • You are not matching 2 digits after AU, and when you repeat the 4 digits you can place the space before the digits.

    ^AU\d\d(?: \d{4}){4} \d\d$
    

    Regex demo

    Or you can use as suggested in the comments by @JvdV repeating 5 times a set of 4 numbers with a space in between:

    ^AU(?:\d\d \d\d){5}$
    

    Regex demo

    Or when also allowing 20 digits with optional spaces in between:

    ^AU\d(?: ?\d){19}$
    

    Regex demo