Validating credit card format using regular expressions?

时光总嘲笑我的痴心妄想 提交于 2019-12-02 23:45:19

问题


I have an assignment that requires me to validate certain credit card formats using regular expressions. For example a MasterCard has 16 digits, starts with a 5 and is followed by 15 digits, so the regular expression would be as follows:

\b5[0-9]{15}\b

What would be the regular expressions for the following credit cards formats?

Diners Club: credit card has 14 digits and begins with either 301, 302, 303, 304, 305, 36 or 38.

JCB: credit card has either 15 digits beginning with either 2131 or 1800, or has 16 digits and begins with 35

Thanks!


回答1:


This should cover all of the bases (provided by RegEx Buddy):

^(?:
(?<visa>4\d{3}[ -]*\d{4}[ -]*\d{4}[ -]*\d(?:\d{3})?) |
(?<mastercard>5[1-5]\d{2}[ -]*\d{4}[ -]*\d{4}[ -]*\d{4}) |
(?<discover>6(?:011|5[0-9]{2})[ -]*\d{4}[ -]*\d{4}[ -]*\d{4}) |
(?<amex>3[47]\d{2}[ -]*\d{6}[ -]*\d{5}) |
(?<diners>3(?:0[0-5]|[68][0-9])\d[ -]*\d{6}[ -]*\d{4}) |
(?<jcb>(?:2131|1800)[ -]*\d{6}[ -]*\d{5}|35\d{2}[ -]*\d{4}[ -]*\d{4}[ -]*\d{4})
)$


来源:https://stackoverflow.com/questions/36537846/validating-credit-card-format-using-regular-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!