4

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?

Archeg
  • 8,364
  • 7
  • 43
  • 90
  • This seems to work on the typescript of [jsfiddle](https://jsfiddle.net/z85dmrcL/), we need more information ... – Alexandre Elshobokshy Jan 29 '19 at 10:40
  • So it's probably the version of typescript that is wrong. Can I change typescript version in jsfiddle? @IslamElshobokshy – Archeg Jan 29 '19 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.. – Archeg Jan 29 '19 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... – Alexandre Elshobokshy Jan 29 '19 at 10:50

2 Answers2

4

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? .

bug-a-lot
  • 2,446
  • 1
  • 22
  • 27
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

ncaq
  • 233
  • 2
  • 9
Jay Wick
  • 12,325
  • 10
  • 54
  • 78