Home > Blockchain >  Typescript how to test if regex is valid without getting syntax error
Typescript how to test if regex is valid without getting syntax error

Time:05-08

I have some code that loads a number of regular expressions from an external source. I would like to test whether a given string is regular regex without crashing the application with a syntax error. I tried using try/catch blocks, but it appears that recent versions of Node will throw a syntax error when trying to parse an invalid expression as a regular expression and I see no way of recovering from a syntax error?

Here is a quick example:

try {
  new RegExp(/?/);
} catch (error) {
  console.log(error)
}

When running this on Node.js or directly in the browser console the catch block will never be resolved, the script just fails.

CodePudding user response:

In your example you are creating a RegExp from a regular expression literal. The compiler is likely catching the illegal expression, so its not even getting as far as a runtime exception.

In your explanation, you say that you are loading regex strings from an external source, and so it seems these would more likely be strings containing a regular expression. In this case, the regular expression will be evaluated at runtime, and you should be able to catch an exception.

In the below snippet, you can see that the RegExp is being created from a string (observe the quotes). Neither the creation nor the test raises an exception, it just reports false for no match.

let r = undefined;
try {
    r = new RegExp('/?/');
    console.log(r.test('abc'));
}
catch (error) {
    console.log('error', error);
}

  • Related