Frage

so i just learned regex today and we didn't get to these symbols /s ^ $

the reason im asking is, firstly i want to know, but i was tasked with writing a regex for all active and common credit cards and the issue i was stuck on is that american express cards have 1 digit less. and didn't know how to write the Regex so that only when the first two digits are 37 (which is American express only) a 15 digit total is allowed.

then i found this:

^((4\d{3})|(5[1-5]\d{2})|(6011)|(34\d{1})|(37\d{1}))-?\s?\d{4}-?\s?\d{4}-?\s?\d{4}|3[4,7][\d\s-]{15}$

and if i take a WORKING CC from Visa lets say (16 digits) and subtract one, it doesn't work, but 15 digits DO WORK with American express, can anyone explain what in the regex does that?

War es hilfreich?

Lösung

Regex

^((4\d{3})|(5[1-5]\d{2})|(6011)|(34\d{1})|(37\d{1}))-?\s?\d{4}-?\s?\d{4}-?\s?\d{4}|3[4,7][\d\s-]{15}$

Regular expression visualization

Debuggex Demo

http://regex101.com/r/yO2sY0

This will describe your regex to you in the bottom...The issue is that your regex isn't valid...

^ this is beginging of string $ end of string \s matches whitespace (spaces, tabs and new lines). \S is negated \s.

The regex isn't valid because of the following

Errors are explained from left to right. Move the mouse cursor over them to see the error highlighted in your pattern

-: Can not form ranges with shorthand properties

Solution

Use the following Regex which is documented here http://www.regular-expressions.info/creditcard.html

^(?:4[0-9]{12}(?:[0-9]{3})?          # Visa
 |  5[1-5][0-9]{14}                  # MasterCard
 |  3[47][0-9]{13}                   # American Express
 |  3(?:0[0-5]|[68][0-9])[0-9]{11}   # Diners Club
 |  6(?:011|5[0-9]{2})[0-9]{12}      # Discover
 |  (?:2131|1800|35\d{3})\d{11}      # JCB
)$

Simplified Regex

\b(?:\d[ -]*?){13,16}\b
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top