Detect unsupported regex features at compile time

Viewed 372

It seems safari has some regex features that are not well supported (lookbehind) even in it's latest version and throws some warnings:

register.js:298 SyntaxError: Invalid regular expression: invalid group specifier

Is there a way to detect, lint or transform those kind of regex automatically with webpack or any other tool at compile time, because those kind of errors tend to slip through tests?

In my case this is the regex causing an error

/(?<!\.|^)\.(?!\.+|$)/

It should match a dot in the middle of the string but not match a succession of dots, I'm trying to get a good equivalent for this regex but I am getting nowhere so far

const tests = [
'test.123.test',
'.test',
'test.',
'test.3..test',
];
//Expected
tests.forEach((test) => console.log(test.split(/(?<!\.|^)\.(?!\.+|$)/)));
//Actual
tests.forEach((test) => console.log(test.match(/^(([^.]*?)(?:\.)([^.]*?))*$/)));

2 Answers

You can use

.match(/^\.+[^.]*|[^.]*\.+$|(?:\.{2,}|[^.])+(?:\.+$)?/g)

See the regex demo. Details:

  • ^\.+[^.]* - one or more dots and then zero or more chars other than a dot
  • | - or
  • [^.]*\.+$ - zero or more chars other than a dot and then one or more dots until string end
  • | - or
  • (?:\.{2,}|[^.])+(?:\.+$)? - one or more two or more dots or any chars other than a dot and then an optional sequence of one or more dots at the end of string.

See a JavaScript demo:

const tests = [
'test.123.test',
'.test',
'test.',
'test.3..test',
'test.3..test.',
'..test.3.test..'
];
for (let test of tests) {
  console.log(test.split(/(?<!\.|^)\.(?!\.+|$)/)); // Expected
  console.log(test.match(/^\.+[^.]*|[^.]*\.+$|(?:\.{2,}|[^.])+(?:\.+$)?/g)); // Actual
}

For the main part of my question, I found an eslint plugin that is able to detect ECMA features (including regex lookbehind) so by enabling the ones known to cause issues, because they can't be transpiled, it will automatically throw an error

{
    "plugins": ["es"],
    "parserOptions": {
        "ecmaVersion": 2018
    },
    "rules": {
        "es/no-async-iteration": "error",
        "es/no-malformed-template-literals": "error",
        "es/no-regexp-lookbehind-assertions": "error",
        "es/no-regexp-named-capture-groups": "error",
        "es/no-regexp-s-flag": "error",
        "es/no-regexp-unicode-property-escapes": "error"
    }
}
Related