5

I have a code line

regex = /^(?<aa>[0-9]{2})-(?<bb>[0-9]{6})-(?<cc>[0-9]{6})-(?<d>[0-9])$/;

And typescript (or is it webpack?) complains:

Module parse failed: Error parsing regular expression: Invalid regular expression: /^(?<aa>[0-9]{2})-(?<bb>[0-9]{6})-(?<cc>[0-9]{6})-(?<d>[0-9])$/: Invalid group (18:23)
    You may need an appropriate loader to handle this file type.

It seems to be a problem with the named groups. This is a valid regex in javascript.

I'm using typescript 2.9.2

I strongly prefer using named groups. What can I do to make them compile?

4
  • This seems to work on the typescript of jsfiddle, we need more information ... Commented Jan 29, 2019 at 10:40
  • So it's probably the version of typescript that is wrong. Can I change typescript version in jsfiddle? @IslamElshobokshy Commented Jan 29, 2019 at 10:47
  • @IslamElshobokshy BTW, wrapping expression in a string (new RegExp("..")) somewhat helps as it seems to switches off compile time validation. Still testing.. Commented Jan 29, 2019 at 10:49
  • I don't think you can change typescript version in jsfiddle, I'm looking into it too. Using RegExp() is a good idea, do keep us updated :-) I can't seem to be able to reproduce, I'm sorry... Commented Jan 29, 2019 at 10:50

2 Answers 2

5

That is actually not a valid regular expression in javascript according to https://regexr.com/. And Firefox and Edge.

Or rather, it depends on the browser. Support for named groups has been added to ES2018. So your mileage might vary.

See http://kangax.github.io/compat-table/es2016plus/ for compatibility.

Typescript compiler is not the one throwing the error it's your webpack module loader. I would try setting the target to ES2018 and see if that works.

Alternatively see the answer about array destructuring on Named capturing groups in JavaScript regex? .

Sign up to request clarification or add additional context in comments.

Comments

1

Unfortunately transpiling the regex itself is not supported by Typescript itself. See issue #24531.

If you're using Babel aswell in your build chain, consider plugin-transform-named-capturing-groups-regex

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.