【问题标题】:Creating Javascript Regex in C++在 C++ 中创建 Javascript 正则表达式
【发布时间】:2017-06-13 00:17:28
【问题描述】:

是否可以在 C++ 中创建 RegExp javascript 对象?我只是好奇。

例子:

const myCLib = require('myCLib');
myCLib("/\\s/", "g"); => return regex object /\g/g

【问题讨论】:

    标签: c++ regex


    【解决方案1】:

    是的,这是自 C++11 以来 C++ 标准的一部分,不需要额外的库。正则表达式的默认语法与 ECMAScript (JavaScript) 的正则表达式语法相同。

    #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)"};
    

    /g 修饰符行为是通过不同地使用正则表达式来实现的,请参阅std::regex equivalent of '/g' global modifier

    【讨论】:

    • 性能取决于您使用的 C++ 实现以及您要解决的特定问题。我能想到三种主要的 C++11 实现,它们各不相同。您始终可以将第三方库用于正则表达式或将正则表达式编译为代码,例如与 Ragel 一起使用,如果您认为值得付出努力,它可以制作出极高性能的解析器。
    猜你喜欢
    • 1970-01-01
    • 2012-01-02
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多