Ajay Patel
Ajay Patel

Reputation: 5418

Regex for first two character of string alphabet and rest should be numeric

I want to validate a string like

Case

  1. Total number of string must be four.
  2. First two character must be alphabet
  3. Last two character must be numeric.

I have used following expression but it can validate only first two character as a Alphabet, how to validate last 2 and total number?

var re = new RegExp('^[a-zA-Z]{2}');
re.test('CC8A8');

Upvotes: 3

Views: 16293

Answers (3)

Rahul
Rahul

Reputation: 3509

Below regex will help you to validate:

var re = new RegExp('^[a-zA-Z]{2}[0-9]{2}$');

Upvotes: 9

anubhava
anubhava

Reputation: 785058

You can use:

var re = /^[a-zA-Z]{2}\d{2}$/;

no need to use RegExp object for this.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Just add the pattern to validate 2 digits at the last.

var re = new RegExp("^[a-zA-Z]{2}\\d{2}$", "m");

Upvotes: 1

Related Questions