4

I've got a problem with c++ regex.
I've got a string like "f 123/123 1234/123/124 12" and I want to get all the numbers before "/".

This is my regexp:

"\s(\d+)".

I tried it on http://rubular.com/ and it works. Here is my code:

std::regex rgx("\\s(\\d+)");
std::smatch match;

if (std::regex_search(line, match, rgx))
{
    std::cout << "Match\n";

    std::string *msg = new std::string();
    std::cout << "match[0]:" << match[0] << "\n";
    std::cout << "match[1]:" << match[1] << "\n";
    std::cout << "match[2]:" << match[2] << "\n";

}

But I get this:

Match
match[0]:123
match[1]:123
match[2]:

I realize that match[0] is not a "groups" like in Python and Ruby.

1 Answer 1

3

regex_search matches once (the first substring that match the regular expression). You need to loop.

Try following:

std::regex rgx("\\s(\\d+)");
std::smatch match;

while (std::regex_search(line, match, rgx))
{
    std::cout << match[0] << std::endl;
    line = match.suffix().str();
}
Sign up to request clarification or add additional context in comments.

2 Comments

@suspectus, Sorry, I misunderstood. You meant a typo. I fixed it. Thank you for pointing that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.