I have a top-level regex variable in JS based on which I later need to do some narrower checks as well for other criteria.
var pattern = /^(EAC|MSC|SRC|IOE|LIN|WAC|NBC|YSC|SSC|ESC|WSC|ZAR|ZBO|ZOL|ZLA|ZNY|ZSF|ZNK|ZHN|ZCH|ZMI|ZDF|ZGA|ZTB)(\*|\d)\d{9}$/;
My new pattern needs to be all Z-prefixed entries here and without the final digits. But I don’t want to redefine a new regex variable as
var pattern2 = /^(ZAR|ZBO|ZOL|ZLA|ZNY|ZSF|ZNK|ZHN|ZCH|ZMI|ZDF|ZGA|ZTB)$/;
It’s possible that the original top-level pattern may change and I don’t want to maintain/duplicate separate variables. If they add a new supported Z.., that should percolate down to the second "Z-only, No-Digits" regex automatically. Is it possible to modify or parse this similar to a string, and have it become a new regex?
>Solution :
Update
Simply use RegExp#source to convert the regex back to string:
console.config({ maximize: true });
const pattern = /^(EAC|MSC|SRC|IOE|LIN|WAC|NBC|YSC|SSC|ESC|WSC|ZAR|ZBO|ZOL|ZLA|ZNY|ZSF|ZNK|ZHN|ZCH|ZMI|ZDF|ZGA|ZTB)(\*|\d)\d{9}$/;
console.log({ pattern, source: pattern.source });
const alternatives = pattern.source.match(/\(([^()]+?)\)/)[1].split('|');
const zPrefixed = alternatives.filter(alt => alt.startsWith('Z'));
console.log({ alternatives, zPrefixed });
const pattern2 = new RegExp(`^(${zPrefixed.join('|')})$`)
console.log(pattern2);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Original
Sure you can, just extract those to variables and use the RegExp() constructor:
const zPrefixed = 'ZAR|ZBO|ZOL|ZLA|ZNY|ZSF|ZNK|ZHN|ZCH|ZMI|ZDF|ZGA|ZTB';
const others = 'EAC|MSC|SRC|IOE|LIN|WAC|NBC|YSC|SSC|ESC|WSC';
const pattern = new RegExp(
String.raw`^(${others}|${zPrefixed})(\*|\d)\d{9}$`
);
const pattern2 = new RegExp(`^(${zPrefixed})$`);
console.config({ maximize: true });
console.log(pattern);
console.log(pattern2);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>