4

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;
}
Nik
  • 9,063
  • 7
  • 66
  • 81
  • To clarify the question, write what you are getting right now. – Dariusz Jan 16 '13 at 14:36
  • Possible duplicate of [Regex to match a C-style multiline comment](https://stackoverflow.com/q/13014947/608639), [Regular expression to find C style block comments](https://stackoverflow.com/q/16160190/608639), etc. – jww May 16 '19 at 19:52

1 Answers1

12

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("/\\*(.*?)\\*/");
Jon
  • 428,835
  • 81
  • 738
  • 806
  • thanks that helped - due to strange new rules I can accept only after 8 min cooldown :) – Nik Jan 16 '13 at 14:37
  • 5
    for some regex engines, for the `.` to match newlines, too, you can change it to this: `[\s\S]` and then it will also match newlines. So in Python this would be: `multi_line_comment = re.compile(r"/\*([\s\S]*?)\*/\s*", re.MULTILINE)` – phyatt Mar 17 '15 at 21:03