开发者

Regex to match card code input

How can I write a regex to matc开发者_运维技巧h 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.


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.


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.


I would start with a tutorial.

Pay attention to the quantifiers (like {N}) and character classes (like [a-zA-Z])


^[a-zA-Z][a-zA-Z0-9]{4} ?[a-zA-Z0-9]{5} ?[a-zA-Z0-9]{3}[\!\&\@\?]$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜