Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for MasterCard

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?

like image 901
Oleg Sh Avatar asked Nov 01 '25 10:11

Oleg Sh


1 Answers

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.
like image 178
Wiktor Stribiżew Avatar answered Nov 02 '25 23:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!