简体   繁体   中英

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]);

\\w matches word characters, which includes _ and digits as well. If you only want to match alphabetical characters, use [az] 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[az][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[az](?=[az\\/-]{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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM