This is a pretty naive attempt at meeting those requirements. The regex will match a series of digits from 15 to 19 digits (the length of credit card numbers varies between providers (ref: Payment_card_number) and it makes no attempt to verify that the card number is actually a credit card number and not, say, some sort of inventory identifier, part number, or other long(ish) string of digits. The regex tries to match the longest string first and then shorter and shorter strings of digits. It may produce false positives if there are non-space characters used to separate the digits. You should do your own testing before relying on it!
$regex = "(?:x)(?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d)| #19 digits
(?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d)| #18 digits
(?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d)| #17 digits
(?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d)| #16 digits
(?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d)" #15 digits
"46604 4567543567", #15
"4660 445 67 5435 67",
"4 6 6044567543 56 7",
"4660445 675 43567",
"4660 44 567543567",
"4660x44 567543567" |
ForEach-Object{
if ($_ -match "\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d ?\d"){
Write-Host "I'm a match: $_" -ForegroundColor Green
}
else{
Write-Host "I'm not a match: $_" -ForegroundColor Yellow
}
}
If there is possibility of finding multiple spaces between the digits you'll have to modify the regex. Here's a brief example of that:
"1 2 3 4" -match "\d ? *?\d ? *?\d ? .*?\d"