Search code examples
phpregexpreg-match

How to make regular expression to detect rupay debit card


Ru pay card start with these following number with 16 digits

  1. 60
  2. 6521
  3. 6522

So how match this formats to get type as it's a rupay type of debit card

I have tried with this regex

/^(((60)([0-9]{14}))|((6521)([0-9]{12}))|((6522)([0-9]{12})))$/

Solution

  • To match both ranges, you could exclude 011 from the first pattern and exclude 521 and 522 from the other pattern.

    To exclude 011 for rupay cards:

    ^6(?!011)(?:0[0-9]{14}|52[12][0-9]{12})$
    

    Explanation

    • ^6 Start of string and match 6
    • (?!011) Assert 011 not directly to the right
    • (?: Non capture group
      • 0[0-9]{14} Match a 0 and 14 digits
      • | Or
      • 52[12][0-9]{12} Match 521 or 522 and 12 digits
    • ) Close group
    • $ End of string

    Regex demo

    To exclude 521 and 522 from discover cards

    ^6(?!52[12])(?:011|5[0-9][0-9])[0-9]{12}$
    

    Explanation

    • ^6 Start of string and match 6
    • (?!52[12]) Assert 521 or 522 not directly to the right
    • (?: Non capture group
      • 011 Match 011
      • | Or
      • 5[0-9][0-9] Match 5 and 2 times a digit 0-9
    • ) Close group
    • [0-9]{12} Match 12 digits
    • $ End of string

    Regex demo