0

Is it possible to create a RegExp javascript object, in C++? I'm just curious about it.

Example:

const myCLib = require('myCLib');
myCLib("/\\s/", "g"); => return regex object /\g/g
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415

1 Answers1

1

Yes, this has been part of the C++ standard since C++11 and no additional libraries are needed. The default syntax for regular expressions is identical to ECMAScript's (JavaScript's) syntax for regular expressions.

#include <regex>

// Note that construction of the regex can be QUITE expensive, and should
// not be done often if you care even a little about performance. Regexes
// are commonly created at global scope.
const std::regex my_regex{"\\s"};

// Raw strings are sometimes more readable...
const std::regex my_regex{R"(\s)"};

The /g modifier behavior is achieved by using the regex differently, see std::regex equivalent of '/g' global modifier

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • 1
    Performance depends on the C++ implementation you use, and the particular problem you're solving. There are three major C++11 implementations I can think of, and they are each different. You can always use a third-party library for regular expressions or compile regexes to code e.g. with Ragel, which can make extremely high-performance parsers if you think it's worth the effort. – Dietrich Epp Jun 13 '17 at 01:23