I have a requirement to keep regex expressions in the database and use them in the application based on different conditions.
Normally the following script works.
For example:
let str: string = "C:\MyFolder\SubFolder";
// When using regex in following way, it works
var regex1 = new RegExp(/^[a-zA-Z]:\\((((?![<>:"/\\|?*]).)+((?<![ .])\\)?)*$)/g);
if (regex1.test(str)) {
console.log("Valid");
} else {
console.log("Invalid");
}
// Output: Valid
But when the same code is modified to use regex from the database it doesn't work.
let str: string = "C:\MyFolder\SubFolder";
// When using regex in following way, it doesn't work
var regex1 = new RegExp(regexFromDB);
if (regex1.test(str)) {
console.log("Valid");
} else {
console.log("Invalid");
}
// Here regexFromDB = "/^[a-zA-Z]:\\((((?![<>:"/\\|?*]).)+((?<![ .])\\)?)*$)/g"
// Output: Invalid
I even tried to replace the double quotes from the regexFromDB
but it didn't work.
Can someone suggest me the right way to use regex from database while keeping the basic requirement of re-usability intact. Thanks