Reputation: 36816
I am looking for a way to detect a credit card within a string using C#. Regex is a possibility. I do not want to detect if a string is a credit card.
For example
string text = "Hi mum, here is my credit card 1234-1234-1223-1234. Don't tell anyone";
bool result = TextContainsCreditCard(text);
if (result)
throw new InvalidOperationException("Don't give people your credit card!");
Upvotes: 1
Views: 1165
Reputation: 1840
You can use the below regex to do it
(\d{4}-?){4}
Here is the sample output with grep.
$ echo "Hi mum, here is my credit card 1234-1234-1223-1234. Don't tell anyone"|grep -Po "(\d{4}-?){4}"
1234-1234-1223-1234
Upvotes: 0
Reputation: 6293
You can use regex like
(\d{4}[\s-]?){4}
And put any chars you want as separator to [\s-]
now they are only space and minus
And this allows separators in any position (\d[\s-]?){16}
like 1 2341234-12341 234
Upvotes: 6
Reputation: 379
Well, if your separator is ONLY spaces or -, then the regex to detect the credit card would be
([0-9]{4}(-| )){3}[0-9]{4}
or maybe there are shorter or better options.
Upvotes: 1
Reputation: 24529
I have drafted this algorithm (would place as comment only it would be badly formatted)
Upvotes: 0