1

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!");
Craig
  • 36,306
  • 34
  • 114
  • 197

4 Answers4

6

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

Pavel Krymets
  • 6,253
  • 1
  • 22
  • 35
1

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.

Kevin Winata
  • 369
  • 3
  • 12
0

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?
jbutler483
  • 24,074
  • 9
  • 92
  • 145
  • 1
    Presumably not everyone will neatly delimit their card numbers – Alex K. Nov 19 '14 at 12:56
  • I'm not great with implementation, but @AlexK. I think checking if there are 16 digits, and ensuring that they form a credit card, is pretty difficult to master a 'perfect' algorithm. – jbutler483 Nov 19 '14 at 13:01
0

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
Kannan Mohan
  • 1,810
  • 12
  • 15