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?
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 222922[3-9][0-9] - 2230 to 22992[3-6][0-9]{2} - 2, then 3 to 6 and any 2 digits (2300 till 2699)27[01][0-9] - 2700 till 27192720  - 2720[0-9]{12} - any 12 digits $ - end of string.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With