Craig
Craig

Reputation: 36816

Find a credit card within a string

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

Answers (4)

Kannan Mohan
Kannan Mohan

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

Pavel Krymets
Pavel Krymets

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

Kevin Winata
Kevin Winata

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

jbutler483
jbutler483

Reputation: 24529

I have drafted this algorithm (would place as comment only it would be badly formatted)

  1. Split string on (-)
  2. See if string contains numeric values.
  3. See if there are 4+ parts
  4. See if parts[0] + parts[1] (i.e. four in a row)
  5. If so, return true, if not, return false?

Upvotes: 0

Related Questions