簡體   English   中英

C ++從regex_iterator獲取匹配項

[英]C++ get matches from regex_iterator

我試圖通過逐行讀取來從文件中獲取一些匹配。 我的代碼是這樣的:

std::regex e("id=\"(.+?)\"|title=\"(.+?)\"|summary=\"(.+?)\"|first=\"(.+?)\"|last=\"(.+?)\"");
std::regex_iterator<std::string::iterator> rit ( line.begin(), line.end(), e );
std::regex_iterator<std::string::iterator> rend;

while (rit!=rend) {
    std::cout << rit->str() << std::endl;
    ++rit;
}

我嘗試過使用regex_search和smatch對象,但它在該行的第一個匹配項中停止。 我發現regex_iterator完成了這項工作,但它給了我整個匹配(例如id =“123456”,而不是123456),這是有道理的,但我只需要數字。

根據http://www.cplusplus.com/reference/regex/regex_iterator/operator * / dereferencing,迭代器會給我一個match_results對象,但我不知道如何聲明一個(它總是給我一個壞參數列表。如何讓迭代器給我一個smatch對象?

match_results對象上調用str()返回整個當前匹配。 要查看單個子匹配,請在調用中傳遞索引:

for (int i = 0; i < rit->size(); ++i)
    std::cout << rit->str(i) << '\n';

您可能必須循環匹配,每次調用regex_match以獲取每次更新的match_results對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM