0

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

Ajendra Prasad
  • 299
  • 1
  • 8
  • 22
  • No need to pass a regex literal to `new RegExp` - just use the regex literal itself. When you have a string to turn into a regex, as in the second code, double-escape the backslashes. – CertainPerformance Jan 04 '19 at 07:46
  • BTW, it should be `let str: string = "C:\\MyFolder\\SubFolder";` – Wiktor Stribiżew Jan 04 '19 at 07:53
  • I tried to replace every single backslash with double backslashes but it makes the string invalid. var regex2 = new RegExp("/^[a-zA-Z]:\\\\((((?![<>:"/\\\\|?*]).)+((?<![ .])\\\\)?)*$)/g"); Seems like I need to disable special meaning for other characters at-least in my case. Can you just give me some idea so I can continue such changes with other regex strings. – Ajendra Prasad Jan 04 '19 at 09:46

0 Answers0