Antonio
Antonio

Reputation: 602

REGEX for Credit Card not working with "or"

I know that regex for some CC are:

If I try them individually they work.
But if I do

^4[0-9]{12}(?:[0-9]{3}) | ^5[1-5][0-9]{14} | ^3[47][0-9]{13} | ^3(?:0[0-5]|[68][0-9])[0-9]{11}

I only got false as return. Should be | as OR?
BTW, need one single regex for all CC. I am doing something wrong?

Upvotes: 0

Views: 137

Answers (3)

pravingaikwad07
pravingaikwad07

Reputation: 522

Try following regex for Credit Card type detection:

        //gemini
        val amex_gemini = "^3[47][0-9]{13}\$"
        val visa_gemini = "^4[0-9]{12}(?:[0-9]{3})?\$"
        val mastercard_gemini = "^5[1-5][0-9]{14}\$"
        val maestro_gemini =
            "^(?:5018|5020|5038|6304|6706|6771)([0-9]{12}|[0-9]{14}|[0-9]{15}|[0-9]{16})\$"
        val rupay_gemini = "^60(?:4|5)[0-9]{13}\$"
        val discover_gemini = "^6011[0-9]{12}\$"
        val jcb_gemini = "^(?:3528|35[3-8][0-9])[0-9]{12}\$"
        val dinersclub_gemini = "^3(?:0[0-5]|[68][0-9])[0-9]{11}\$"

        //chatgpt
        val amex_cgpt = "^3[47][0-9]{13}\$"
        val visa_cgpt = "^4[0-9]{12}(?:[0-9]{3})?\$"
        val mastercard_cgpt = "^5[1-5][0-9]{14}\$|^2[2-7][0-9]{14}\$"
        val maestro_cgpt = "^(5[0678]\\d\\d|6304|6390|67\\d\\d)\\d{8,15}\$"
        val rupay_cgpt = "^(60[0-9]{14}|65[0-9]{14}|81[0-9]{14})\$"
        val discover_cgpt =
            "^6(?:011|5[0-9]{2}|4[4-9][0-9])[0-9]{12}\$|^6(?:22[1-9][0-9]{0,2}|22[2-8][0-9]{1,3}|229[0-2][0-9]{1,2}|2293[0-5])[0-9]{10}\$"
        val jcb_cgpt = "^35[0-9]{14}\$"
        val dinersclub_cgpt = "^3(?:0[0-5]|[68][0-9])[0-9]{11}\$"
        val unionpay_cgpt = "^62[0-9]{14,17}\$"
        val visaelectron_cgpt = "^(4026|417500|4508|4844|4913|4917)\\d{12}\$"
        val instapayments_cgpt = "^63[7-9][0-9]{13}\$" 

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627409

It is correct that a caret is a beginning of a string and a pipe is an alternation operator. However, spaces inside are only insignificant when a VERBOSE/comment/freespace mode is on.

It is safer to remove those spaces, and also add the end of line anchor ($):

^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])‌​[0-9]{11})$

Upvotes: 2

Federico Piazza
Federico Piazza

Reputation: 31035

Additionaly to Wiktor Stribiżew answer, for your kind of scenarios a nice way to understand and to improve regexs is by using a tool like debuggex.

So, if I use your expression you can easily see the issues you have. For instance, this is the case for your expression:

Regular expression visualization

As you can see, there some spaces (shown with _). There are clearly some typos.

So, you can improve and fix your regex by using:

^(?:4[0-9]{15}|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])‌​[0-9]{11})$

Regular expression visualization

Upvotes: 2

Related Questions