Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

regex

I'm trying to implement simple case (basically find text between two tags whatever they are). I want to get lines

/* my comment 1 */

/* my comment 2 */

/* my comment 3 */

as an output. It seems I need to limit capture group to 1? Because on string Hello /* my comment 1 */ world I get what I want - res[0] contains /* my comment 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;
}
like image 493
Nik Avatar asked Sep 05 '25 23:09

Nik


1 Answers

Make the regular expression only match up to the first occurrence of */ by turning the quantifier * into its non-greedy version. This is accomplished by adding a question mark after it:

std::regex rx("/\\*(.*?)\\*/");
like image 158
Jon Avatar answered Sep 08 '25 23:09

Jon