简体   繁体   中英

std::regex_search return multiple matches

In regex engines that I'm familiar with, it's possible to return every instance of a matching substring. Eg the following Perl code gives the output shown:

my $data = "one two three four";
my @result = ($data =~ /(\w+)/g);
say "@result";

output:

one two three four

So all four matches are returned, when the "g" modifier is used. If I try to do the same thing using std::regex_search, only the first match is returned. Ie:

    std::string  srchStr  = "one two three four";
    std::regex   r("(\\w+)");
    std::smatch  m;

    if (regex_search(srchStr, m, r)) {
        std::cout << "m.size()=" << m.size() << std::endl;
        for (const std::string &s : m) {
            std::cout << s << std::endl;
        }
    }

output:

m.size()=2
one
one

Is there something like the g operator in perl that will cause it to return all the matches? Thanks

You use std::sregex_iterator :

#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string const s{"one two three four"};
    std::regex const r{"(\\w+)"};

    for (std::sregex_iterator it{s.begin(), s.end(), r}, end{}; it != end;
         ++it) {
        std::cout << it->str() << '\n';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM