Exception
Exception

Reputation: 8379

Regular expression to accept 4 chars with different pattern

I am trying for a regular expression for below requirement.

  1. Total string length must be 3 or 4.
  2. First two characters must be from a-z or A-Z
  3. Last two characters must be from 0-9

I have tried the below, but I know this is not the good way

     var str = /^[a-zA-Z]{1,2} + [0-9]{2} + $/,   

Please help me on this.

Upvotes: 0

Views: 98

Answers (1)

Andreas Wong
Andreas Wong

Reputation: 60516

var str = /^([a-z]{1,2}|[A-Z]{1,2})[0-9]{2}$/;

Then you test it as:

str.test("aa3"); // false, 2 integers are required
str.test("a34"); // true
str.test("aA33"); // false, 2 first characters have to be in the same case

Not sure what you really mean by First two characters must be from a-z or A-Z, if you want those characters to be the same cases, use the regex above, otherwise

var str = /^[a-zA-Z]{1,2}[0-9]{2}$/;

Upvotes: 4

Related Questions