2012-03-22 53 views
2

不同的結果我只是想獲取給定的字符串正則表達式的讀取與regex_search

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

#include <conio.h> 
using namespace std; 

int main() { 
    std::tr1::cmatch res; 
    string str; 
    str = "a lot of unknown text here<h2>Test2 12</h2> a lot of unknown text here <h2>Test3 45</h2>a lot of text here too"; 
    std::tr1::regex rx("Test(\d+) (\\d+)"); 
    std::tr1::regex_search(str.c_str(), res, rx); 
    std::cout << "RES 1: " << res[1] << ". " << res[2] << "\n"; 
    std::cout << "RES 2: " << res[3] << ". " << res[4] << "\n"; 
    return 0; 
} 

我希望它能夠從一個得到同時搜索結果的結果,例如:

數組1:[1] = 2,[2] = 12和 數組2:[1] = 3,[2] = 45或者它可以是這樣的:[1] = 2,[2] = 12,[ 3] = 3,[4] = 45

我該怎麼做?如果我使用不正確的功能,告訴我哪個功能以及如何使用它來做我在這裏問的問題。 我希望我已經清楚, 在此先感謝。

回答

2

你在找什麼是regex_iterator類模板。在您的例子:

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

int main() { 
    std::string str("a lot of unknown text here<h2>Test2 12</h2> a lot of unknown text here <h2>Test3 45</h2>a lot of text here too"); 
    std::tr1::regex rx("Test(\\d+) (\\d+)"); 
    std::tr1::sregex_iterator first(str.begin(), str.end(), rx); 
    std::tr1::sregex_iterator last; 

    for (auto it = first; it != last; ++it) 
    { 
     std::cout << "[1]=" << it->str(1) << " [2]=" << it->str(2) << std::endl; 
    } 

    return 0; 
} 

另外,還可以用regex_token_iterator類模板實現您的選項號2:

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

int main() 
{ 
    std::string str("a lot of unknown text here<h2>Test2 12</h2> a lot of unknown text here <h2>Test3 45</h2>a lot of text here too"); 
    std::tr1::regex rx("Test(\\d+) (\\d+)"); 
    int fields[2] = { 1, 2 }; 
    std::tr1::sregex_token_iterator first(str.begin(), str.end(), rx, fields); 
    std::tr1::sregex_token_iterator last; 

    std::size_t i = 0; 
    for (auto it = first; it != last; ++it) 
    { 
     std::cout << "[" << i << "]=" << it->str() << std::endl; 
     ++i; 
    } 

    return 0; 
} 
+0

謝謝你,這就是我一直在尋找。 :D – Grego 2012-03-22 14:31:34

+0

+1 for'sregex_iterator';) – LihO 2012-04-20 13:20:05