PowerShell RE to match credit card patterns

I recently needed to come up with a credit card pattern that would match most credit card patterns including spaces and dashes.

I found a helpful post about PowerShell and credit card pattern matches that was a helpful starting point here: http://technet.microsoft.com/en-us/query/cc434704

I ended up with the following 2 patterns.

For Visa, MC and Discover:

“((4\d{3})|(5[1-5]\d{2})|(6011|65\d{2}))[-| ]*\d{4}[-| ]*\d{4}[-| ]*\d{4}$”


“3[47]\d{2}[-| ]*\d{6}[-| ]*\d{5}$”

It is relevant to note that I needed to NOT have a space between the first ” and the first number.  In addition, the $ was required so strings larger than the specified number were not matched.  So for example, a string that was 18 digits starting with 4 would not be matched.

The actual PowerShell command I used was:

Get-ChildItem -rec -exclude *.exe,*.dll | select-string “3[47]\d{2}[-| ]*\d{6}[-| ]*\d{5}$”

I ran it in a test directory with files including VALID and INVALID credit card patterns.

Actual patterns that worked and didn’t block false positives.

“^3[47]\d{13}$” (no spaces)

“^3[47]\d{2}-\d{6}-\d{5}$” (with dashes)
“^3[47]\d{2} \d{6} \d{5}$” (with spaces)



^((4\d{3})|(5[1-5]\d{2})|(6011|65\d{2})) \d{4} \d{4} ?\d{4}$