繁体   English   中英

std::regex_search 返回多个匹配项

[英]std::regex_search return multiple matches

在我熟悉的正则表达式引擎中,可以返回匹配 substring 的每个实例。例如,以下 Perl 代码给出了所示的 output:

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

output:

one two three four

因此,当使用“g”修饰符时,将返回所有四个匹配项。 如果我尝试使用 std::regex_search 做同样的事情,则只返回第一个匹配项。 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

perl 中是否有类似 g 运算符的东西会导致它返回所有匹配项? 谢谢

您使用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';
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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