[英]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:在我熟悉的正则表达式引擎中,可以返回匹配 substring 的每个实例。例如,以下 Perl 代码给出了所示的 output:
my $data = "one two three four";
my @result = ($data =~ /(\w+)/g);
say "@result";
output: output:
one two three four
So all four matches are returned, when the "g" modifier is used.因此,当使用“g”修饰符时,将返回所有四个匹配项。 If I try to do the same thing using std::regex_search, only the first match is returned.
如果我尝试使用 std::regex_search 做同样的事情,则只返回第一个匹配项。 Ie:
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: output:
m.size()=2
one
one
Is there something like the g operator in perl that will cause it to return all the matches? perl 中是否有类似 g 运算符的东西会导致它返回所有匹配项? Thanks
谢谢
You use std::sregex_iterator :您使用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.