2014-11-23 22 views
1

我正在閱讀關於std::regex_iterator<std::string::iterator>的文檔,因爲我試圖學習如何使用它來解析HTML標記。該網站給出的例子是根據CPlusPlus.com使用std :: regex_iterator <std :: string :: iterator>

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

int main() 
{ 
    std::string s ("this subject has a submarine as a subsequence"); 
    std::regex e ("\\b(sub)([^ ]*)"); // matches words beginning by "sub" 

    std::regex_iterator<std::string::iterator> rit (s.begin(), s.end(), e); 
    std::regex_iterator<std::string::iterator> rend; 

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

    return 0; 
} 

http://www.cplusplus.com/reference/regex/regex_iterator/regex_iterator/

和我有一個問題:如果rend從未初始化,那麼它是如何被有意義的rit!=rend使用?

此外,我應該用什麼工具獲取HTML標籤的屬性?我想要做的就是有一個字符串像"class='class1 class2' id = 'myId' onclick ='myFunction()' >"並打破成對

"class""class1 class2"),("id""myId"),("onclick""myFunction()"

,然後與他們從那裏工作。正則表達式我打算用的是

([A-Za-z0-9\\-]+)\\s*=\\s*(['\"])(.*?)\\2 

,所以我打算通過這種類型的表達式循環遍歷同時跟蹤我是否仍然在標籤(即,是否我通過一個'>'字符)。這樣做太難了嗎?

感謝您爲我提供的任何指導。

回答

3

你是什麼意思「如果rend永遠不會初始化」?顯然,std::regex_iterator<I>有一個默認的構造函數。由於迭代只是前向迭代,所以結束迭代器只需要適合檢測結束就可以使用。默認構造函數可以相應地設置rend

這是在標準C++庫中的其他地方使用的一個習語,例如std::istream_iterator<T>。理想情況下,可以使用不同類型指示結束迭代器(有關此問題,請參閱Eric Niebler's discussion,鏈接是四頁中的第一頁),但標準當前要求使用算法時兩種類型匹配。

關於使用正則表達式解析HTML請參閱this answer

1

rend不是未初始化的,它是默認構造的。您鏈接的頁面明確指出:

默認構造函數(1)構造序列結束迭代器。

由於缺省結構似乎是獲得結束序列的迭代器的唯一辦法,比較ritrend是測試rit是否耗盡的正確方法。

相關問題