簡體   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