Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify/parse declared regex variable into a new regex in JS

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading