1

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?

anubhava
  • 761,203
  • 64
  • 569
  • 643
Giladiald
  • 857
  • 3
  • 9
  • 17
  • 1
    Did you [read the manual](http://php.net/manual/en/reference.pcre.pattern.syntax.php)? – John Conde Dec 06 '13 at 16:19
  • 3
    [Read the manual](http://php.net/manual/en/reference.pcre.pattern.syntax.php). Break down the regex into its *simplest* parts. Work out what each one does. Don't be intimidated by the mass of line noise in front of you. Nobody can digest the whole thing in one bite. Just break it down and work your way back up from the simplest components. – 15ee8f99-57ff-4f92-890c-b56153 Dec 06 '13 at 16:23
  • 1
    Question title and question body don't match at all. Title is about meaning of `\s ^ $` and body is about validating AMEX card # – anubhava Dec 06 '13 at 16:24
  • qwrrty why is it mistaken? and what does \s- actually mean? – Giladiald Dec 06 '13 at 16:43

1 Answers1

1

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
abc123
  • 17,855
  • 7
  • 52
  • 82