How to use regex c ++?

I am having a problem with C ++ regex. I got a line like "f 123/123 1234/123/124 12" and I want to get all the numbers up to "/".

This is my regexp: "\ s (\ d +)". I tried it at 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 the following:

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

I understand that match [0] is not a "group", as in Python and Ruby. Thanks and sorry for my english :)

+4
source share
1 answer

regex_searchmatches once (the first substring matching the regular expression). You need to go in cycles.

Try the 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();
}
+3
source

Source: https://habr.com/ru/post/1526025/


All Articles