Home > Software engineering >  C Regex: Matching words after hyphens
C Regex: Matching words after hyphens

Time:11-07

I am a bit new to C regex and trying to make a regex work. Basically, I want to match "the pickle" in the following sentence:

I      pick picked   --  the pickle

To implement this, I am using the following regex --> std::regex reg3 ("(--)[\\s]*. ")

However,my output is the following:

--  the pickle

My desired output is:

the pickle

Any idea, how I should modify my regular expression to not pick up the hyphens (--) and the spaces?

CodePudding user response:

You can use the capture groups () to delineate submatches:

#include <regex>
#include <iostream>

int main() {
    std::string txt = "I pick picked -- the pickle";

    std::regex re(R"(--\s*(. ))");
    std::smatch m;

    if (std::regex_search(txt, m, re)) {
        std::cout << "Full match: " << m.str() << "\n";
        std::cout << "Groups: " << m.size() << "\n";
        std::cout << "First paren capture group: " << m[1] << "\n";
    }
}

Prints

Live On Coliru

Full match: -- the pickle
Groups: 2
First paren capture group: the pickle
  • Related