NAPI: How to match a JS regex from a C++ thread?

187 Views Asked by At

I am modifying a Node native extension that is spawning native threads to do some processing. My issue is that I'd like to have the Javascript code provide a filter for the processing to exclude some data.

At this point, I'm passing a JS RegExp string from JS to C++, creating a std::regex instance from it, and passing it around the different structures down to the native thread logic.

My issue now is that despite std::regex using what seems to be the same syntax as ECMAScript regular expressions, the behavior is not the same :(

My original plan was to rely on V8's RegExp engine somehow but trigger the C++ bits directly instead of going from C++ to JS and back. But I wasn't able to find how to do this.

As example, see the following programs using the same regex but yielding different results:

#include <stdio.h>
#include <regex>

int main() {
  std::regex re("^(?:(?:(?!(?:\\/|^)\\.).)*?\\/c)$");
  std::smatch match;
  std::string input("a.b/c");
  int result = std::regex_match(input, match, re);
  if (result == 1) {
    printf("ok");
  } else {
    printf("nok");
  }
  return 0;
}

The equivalent JS code:

const re = new RegExp("^(?:(?:(?!(?:\\/|^)\\.).)*?\\/c)$");
const match = re.exec("a.b/c");
if (match) {
  console.log("ok");
} else {
  console.log("nok");
}

My question then is: What can I do to get the same results I would in JS but in C++? Is it possible to run V8's RegExp from a pure C++ context?

0

There are 0 best solutions below