Akki
Akki

Reputation: 1778

How to write regex in JS for first 2 characters can be digit or alphabet and followed by hyphen and then 6 digit number?

I am trying to create the regex for following format:

12-345678  Matches
AB-345678  Matches

$12-345678 Failed
%%-SDdfdf  Failed
  1. First 2 characters should be alphabet or digit example AA or 12
  2. Third character should be compulsory -(hyphen) and
  3. Last six characters should be digit
  4. String should not be greater than 9 characters long

I have written following Regex but it is failing:

$('#customer-number').keyup(function(){
$(this).val($(this).val().replace(/^(d{2}|[a-z]{2})\-\\d{6}/,'$1-'))
});

But the Regex fails:

/^(d{2}|[a-z]{2})\-\\d{6}/

I am new to regex, please help me

Upvotes: 0

Views: 1327

Answers (3)

Mamun
Mamun

Reputation: 68933

Try the following

/^[a-zA-Z0-9]{2}-\d{6}/

Where

^ asserts position at start of a line

a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)

A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)

{2} Quantifier — Matches exactly 2 times

- matches the character - literally

\d matches a digit (equal to [0-9])

{6} Quantifier — Matches exactly 6 times

Demo:

console.log(/^[a-zA-Z0-9]{2}-\d{6}/.test('12-345678'));  //true
console.log(/^[a-zA-Z0-9]{2}-\d{6}/.test('AB-345678'));  //true
console.log(/^[a-zA-Z0-9]{2}-\d{6}/.test('$12-345678')); //false
console.log(/^[a-zA-Z0-9]{2}-\d{6}/.test('%%-SDdfdf'));  //false

Upvotes: 1

Basil Abubaker
Basil Abubaker

Reputation: 1651

Try This regex /^([a-zA-Z]{2}|[0-9]{2})-\d{6}/g

function matchString() { 
        var test1 = "11-122121";
        var test2 = "1a-122121"; 
        var test3 = "aa-122121"; 
        var result1 = test1.match(/^([a-zA-Z]{2}|[0-9]{2})-\d{6}/g); 
        var result2 = test2.match(/^([a-zA-Z]{2}|[0-9]{2})-\d{6}/g); 
        var result3 = test3.match(/^([a-zA-Z]{2}|[0-9]{2})-\d{6}/g); 
        document.write("Output1 : " + result1 + "<br>");         
        document.write("Output2 : " + result2 + "<br>");
        document.write("Output3 : " + result3);
    } matchString();

Upvotes: 1

Beno&#238;t Zu
Beno&#238;t Zu

Reputation: 1287

You missed \ before d, you need to add A-Z for uppercase and you added a \ that escape the other \.

^(\d{2}|[a-zA-Z]{2})\-\d{6}

Demo: https://regex101.com/r/SEQGOq/1

Upvotes: 1

Related Questions