nim-lang / needed-libraries

This repository contains a list a needed libraries.
112 stars 5 forks source link

JS regex wrapper #114

Closed metagn closed 4 years ago

metagn commented 4 years ago

There's regex libraries that wrap PCRE and ones written in pure Nim, yet none that uses pure JS regex syntax. This would be a start:

type RegExp {.importc: "RegExp".} = ref object

proc escapeSlashes(s: string): string =
  var escaped = false
  for ch in s:
    if escaped or ch == '/':
      result.add('\\')
      result.add(ch)
      escaped = false
    elif ch == '\\':
      escaped = true
    else:
      result.add(ch)

proc re(str: static[string]): RegExp =
  {.emit: [result, " = /", escapeSlashes(str), "/;"].}

let regexp = re"aDa+dd"

Of course you could also wrap new RegExp but MDN says it's slower for constant patterns.

Araq commented 4 years ago

MDN says it's slower for constant patterns.

I doubt it, modern JITs should be really good at it.

metagn commented 4 years ago

That's what I thought at first. MDN link. There are also some benchmarks online if you search "regexp constructor vs literal", this one shows a 3x speedup on Chrome. Doesn't seem like it's going to be that much of a difference in realtime though if it's still millions of operations per second.

ghost commented 4 years ago

jsre is now in devel.