Dibish
Dibish

Reputation: 9293

Regular expression for an alphanumeric word start with alphabet

I have a requirement to find and return the first occurrence of the pattern from a string.

Example: Please find my model number RT21M6211SR/SS and save it

Expected output: RT21M6211SR/SS

Condition for the pattern to match

  1. Combination of digits and alphabets
  2. Character length between 6 to 14
  3. May or may not contain special characters like '-' or '/'
  4. Starts with always alphabet

What I tried, but it didn't work for 4th condition

var str = 'Please find my model number RT21M6211SR/SS and save it';
var reg = /\b(\w|\d)[\d|\w-\/]{6,14}\b/;
var extractedMNO = '';
var mg = str.match(reg) || [""];
console.log('regular match mno', mg[0]);

Upvotes: 1

Views: 1261

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

\w matches word characters, which includes _ and digits as well. If you only want to match alphabetical characters, use [a-z] to match the first character.

Also, because you want to match lengths of 6-14, after matching the first character, you should repeat the character set with {5,13}, so that the repeated characters plus the first character comes out to a length of 6-14 characters.

var str = 'Please find my model number RT21M6211SR/SS and save it';
console.log(str.match(/\b[a-z][a-z0-9\/-]{5,13}/gi)[2]);

But since the matched string must contain digits (and doesn't just permit digits), then you need to make sure a digit exists in the matched substring as well, which you can accomplish by using lookahead for a digit right after matching the alphabetical at the start:

var str = 'Please find my model number RT21M6211SR/SS and save it';
console.log(str.match(/\b[a-z](?=[a-z\/-]{0,12}[0-9])[a-z0-9\/-]{5,13}/gi));
//                            ^^^^^^^^^^^^^^^^^^^^^^^

If you want to permit other special characters, just add them to the character set(s).

Upvotes: 2

Related Questions