Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
883 views
in Technique[技术] by (71.8m points)

regex - Validating credit card format using regular expressions?

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:

5[0-9]{15}

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

^(?:
(?<visa>4d{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}|35d{2}[ -]*d{4}[ -]*d{4}[ -]*d{4})
)$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...