4

I found the following regex for credit card type MasterCard

public static readonly string CreditMasterCard = @"^(5[1 - 5][0 - 9]{14})$";

then I wrote the following code:

Regex regexMasterCard = new Regex(CommonLibrary.RegexCreditCardStrings.CreditMasterCard);

if (regexMasterCard.IsMatch(number)) return CommonLibrary.CreditCardType.mastercard;

But when I set number='5308171154251187' it's wrong. What is incorrect in regex?

PaulG
  • 13,871
  • 9
  • 56
  • 78
Oleg Sh
  • 8,496
  • 17
  • 89
  • 159

1 Answers1

7

You just need to remove the spaces inside the character classes:

^5[1-5][0-9]{14}$

Those spaces are always meaningful inside a character class (even if you specify the RegexOptions.IgnorePatternWhitespace flag) and in your case they created ranges from space to space, not from 1 to 5 and 0 to 9 digits. Also, there is no need in the outer parentheses, you do not need to capture the whole pattern (you can always refer to the whole match with $0 backreference or match.Value).

See the regex demo.

As per @saj comment, you may now use

^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$

See the regex demo

Details:

  • ^ - start of string
  • (?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720) - any of the alternatives:
    • 5[1-5][0-9]{2} - 5, a 1 to 5 and any 2 digits (5100 to 5599)
    • 222[1-9] - 2221 to 2229
    • 22[3-9][0-9] - 2230 to 2299
    • 2[3-6][0-9]{2} - 2, then 3 to 6 and any 2 digits (2300 till 2699)
    • 27[01][0-9] - 2700 till 2719
    • 2720 - 2720
  • [0-9]{12} - any 12 digits
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 3
    MasterCard has now started numbers 2221 through 2720. All have 16 digits.So use this regex,^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$ – sajanyamaha Aug 07 '17 at 10:27
  • You can probably shorten the regex with replacing all `[0-9]` with `\d` -s. – Andres Jul 23 '19 at 07:18
  • 2
    @AndresEhrenpreis [I am not sure it is a good idea](https://stackoverflow.com/a/16621778/3832970). – Wiktor Stribiżew Jul 23 '19 at 11:20