Mujtaba
Mujtaba

Reputation: 260

Regex to extract Credit Card information

I have some data from which I only want to extract Card details i.e. Card number, Expr month/Year and Cvv. I tried many patterns but none of them worked for both of them. If one gets matched then the other wont.

Test Data:

4400634848591837Cvv: 362Expm: 04Expy: 20
4400634848591837:04 20 362
4400634848591837|04/24 362
4400634848591837 0420 362

Regex:

(\d{16})[\/\s:|]*?(\d\d)[\/\s|]*?(\d{2,4})[\/\s|-]*?(\d{3})

This matches the rest of them but I haven't figured out how to match first line. I have tried +- Lookahead & Lookbehind but It never worked for me. So any help would be great.

Demo: Here

Upvotes: 2

Views: 903

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

The part after the 16 digits for the first line has a different format, and the order of the values is also different.

You can use an alternation | with 3 groups to get the values vor the Cvv part.

Note that you don't have to make the character class [\/\s|-]*? non greedy using the ? as the characters can not cross matching the digits that follow.

\b(\d{16})(?:[\/\s:|]*(\d\d)[\/\s|]*(\d{2,4})[\/\s|-]*(\d{3})|Cvv:\s*(\d{3})Expm:\s*(\d\d)Expy:\s*(\d\d))\b
  • \b A word boundary to prevent a partial match
  • (\d{16})(?:[\/\s:|]*(\d\d)[\/\s|]*(\d{2,4})[\/\s|-]*(\d{3}) The pattern for the last 3 lines
  • | Or
  • Cvv:\s*(\d{3})Expm:\s*(\d\d)Expy:\s*(\d\d)) The pattern for the first line, matching the texts in the line followed by capturing the digits in 3 groups
  • \b A word boundary

Regex demo

Upvotes: 1

Related Questions