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

C++ regex search for multi-line comments (between /* */)

本文关键字:之间 正则表达式 搜索 多行注释 c++      更新时间:2023-10-16

我试图实现简单的情况(基本上找到两个标签之间的文本,无论它们是什么)。我想要得到lines

/* my comment 1 */

/* my comment 2 */

/* my comment 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;
}

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

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