0

This question is specifically about a transpiler or transpiler extension. RegExp() is object-creation is massively slower and constructs the RegExp on each iteration.

It seems JavaScript does't permit insensitive whitespace in its regex. Is there any transpiler for JavaScript that permits something like /x from perl, in the Regex.

/x and /xx A single "/x" tells the regular expression parser to ignore most whitespace that is neither backslashed nor within a bracketed character class. You can use this to break up your regular expression into more readable parts. Also, the "#" character is treated as a metacharacter introducing a comment that runs up to the pattern's closing delimiter, or to the end of the current line if the pattern extends onto the next line. Hence, this is very much like an ordinary Perl code comment. (You can include the closing delimiter within the comment only if you precede it with a backslash, so be careful!)

This allows you to write something like

let res = name.match(/^([^\d]*?)(?:\s*[.,]\s*([0-9]+)(?: mo)?)?[.,]?$/);

Like this,

let res = name.match(/
  ^
  ([^\d]*?)                       # name
  (?:\s*[.,]\s*([0-9]+)(?: mo)?)? # age, mo
  [.,]?                           # trailing dirt
  $
 /);
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • Updated the question: This question is specifically about a transpiler or transpiler extension. RegExp() is object-creation is massively slower and constructs the RegExp on each iteration. – Evan Carroll Dec 16 '18 at 22:14
  • 1
    Just use the JS equivalent of Perl's `state re = qr/.../;`, which would be something along the lines of `persistent_var ||= new RegExp(...);`. – ikegami Dec 16 '18 at 22:20
  • If you're specifically asking for a tool, then this is off topic anyway. – jonrsharpe Dec 16 '18 at 22:29
  • @ikegami that incurs a runtime compilation cost every time the pattern is encountered which is pretty substantial. – Evan Carroll Dec 16 '18 at 22:31
  • No, the cost only occurs once. – ikegami Dec 16 '18 at 22:32
  • @ikegami [**benchmark**](http://javascript-benchmark.info/NhN) – Evan Carroll Dec 16 '18 at 22:32
  • My bad. That I didn't see. That would work to do what I want as a workaround. I'm going to see if I can write that into a transpiler and self-answer with that. You want to write that as an answer, I'll mark it for now. – Evan Carroll Dec 16 '18 at 23:08
  • Hmmm, did you post the wrong link? That doesn't use my solution. [Fixed benchmark](http://javascript-benchmark.info/ThN/1) – ikegami Dec 16 '18 at 23:21
  • @ikegami as a side note, there are some differences from regex-literal notations and RegExp objects https://stackoverflow.com/a/17863171/124486 – Evan Carroll Dec 17 '18 at 03:48

1 Answers1

1

I believe you're looking for something exactly like this: https://www.npmjs.com/package/babel-plugin-transform-modern-regexp

starbelly
  • 254
  • 1
  • 4