Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match card code input

How can I write a regex to match strings following these rules?

  • 1 letter followed by 4 letters or numbers, then
  • 5 letters or numbers, then
  • 3 letters or numbers followed by a number and one of the following signs: ! & @ ?

I need to allow input as a 15-character string or as 3 groups of 5 chars separated by one space.

I'm implementing this in JavaScript.

like image 417
kate Avatar asked Feb 03 '26 06:02

kate


2 Answers

I'm not going to write out the whole regex for you since this is homework, but here are some hints which should help you out:

  • Use character classes. [A-Z] matches all uppercase. [a-z] matches all lowercase. [0-9] matches numbers. You can combine them like so [A-Za-z0-9].
  • Use quantifiers like {n} so [A-Z]{3} gives you 3 uppercase letters.
  • You can put other characters in character classes. Let's say you wanted to match % or @ or #, you could do [%@#] which would match any of those characters.
  • Some meta-characters (characters which have special meaning in the context of regular expressions) will need to be escaped like so: \$ (since $ matches the end of a line)
  • ^ and $ match the beginning and end of the line respectively.
  • \s matches white-space, but if you sanitize your input, you shouldn't need to use this.
  • Flags after the regex do special things. For example in /[a-z]/i, the i ignores case.
like image 70
Vivin Paliath Avatar answered Feb 04 '26 18:02

Vivin Paliath


This should be it:

/^[a-z][a-z0-9]{4} ?[a-z0-9]{5} ?[a-z0-9]{3}[0-9][!&@?]$/i

Feel free to change 0-9 and [0-9] with \d if you see fit.
The regex is simple and readable enough. ^ and $ make sure this is a whole match, so there aren't extra characters before or after the code, and the /i flag allows upper or lower case letters.

like image 20
Kobi Avatar answered Feb 04 '26 20:02

Kobi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!