Вы можете сделать свое регулярное выражение /^\w{3}(SQ|MI)([0-9]{5})?$/i
, сделать необязательные 0-5 цифр, добавив ?
, а также заключить его в скобки, так как вы хотите захватить его.
const regex = /^\w{3}(SQ|MI)([0-9]{5})?$/i;
const case1 = 'ABCSQ12345';
const case2 = 'XYZMI32134';
const case3 = 'ABCSQ';
const case4 = 'Something Irrelevant';
let result;
if(result = case1.match(regex)) {
// it will enter, and capture "12345"
const capture = result[2];
console.log('case 1:', capture);
}
if(result = case2.match(regex)) {
// it will enter, and capture "32134"
const capture = result[2];
console.log('case 2:', capture);
}
if(result = case3.match(regex)) {
// it will also enter, but capture is empty
const capture = result[2];
console.log('case 3:', capture);
}
if(result = case4.match(regex)) {
// it will not enter here, since the given string doesn't match the pattern
const capture = result[2];
console.log('case 4:', capture);
}