C++正则表达式搜索多行注释(在/**/之间)

Nik*_*Nik 0 c++ regex

我正在尝试实现简单的情况(基本上在两个标签之间找到文本,无论它们是什么).我想要排队

/*我的评论1*/

/*我的评论2*/

/*我的评论3*/

作为输出.看来我需要将捕获组限制为1?因为在字符串上Hello /* my comment 1 */ world我得到了我想要的东西 - res [0]包含/*我的评论1*/

#include <iostream>
#include <string>
#include <regex>

int main(int argc, const char * argv[])
{
    std::string str = "Hello /* my comment 1 */ world /* my comment 2 */ of /* my comment 3 */ cpp";

    std::cmatch res;
    std::regex rx("/\\*(.*)\\*/");

    std::regex_search(str.c_str(), res, rx);

    for (int i = 0; i < sizeof(res) / sizeof(res[0]); i++) {
        std::cout << res[i] << std::endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 10

通过将量词转换为非贪婪版本,使正则表达式仅匹配第一次出现.这是通过在其后添加问号来完成的:*/*

std::regex rx("/\\*(.*?)\\*/");
Run Code Online (Sandbox Code Playgroud)

  • 对于一些正则表达式引擎,对于`.`来匹配换行符,你可以将它改为:`[\ s\S]`然后它也匹配换行符.所以在Python中,这将是:`multi_line_comment = re.compile(r"/\*([\ s\S]*?)\*/\s*",re.MULTILINE) (2认同)