2014-02-09 109 views
4

我得到了一個C++正則表達式的問題。 我得到了一個像「f 123/123 1234/123/124 12」的字符串,我想在「/」之前得到所有數字。如何使用正則表達式C++?

這是我的正則表達式:「\ s(\ d +)」。我在http://rubular.com/上試過了,它工作。 這裏是我的代碼:

std::regex rgx("\\s(\\d+)"); 
std::smatch match; 

if (std::regex_search(line, match, rgx)) 
{ 
    std::cout << "Match\n"; 

    std::string *msg = new std::string(); 
    std::cout << "match[0]:" << match[0] << "\n"; 
    std::cout << "match[1]:" << match[1] << "\n"; 
    std::cout << "match[2]:" << match[2] << "\n"; 

} 

,但我得到這樣的:

Match 
match[0]:123 
match[1]:123 
match[2]: 

我意識到比賽[0]不是 「集團」 像Python和Ruby。感謝和對不起我的英語:)

回答

3

regex_search匹配一次(匹配正則表達式的第一個子字符串)。你需要循環。

嘗試以下操作:

std::regex rgx("\\s(\\d+)"); 
std::smatch match; 

while (std::regex_search(line, match, rgx)) 
{ 
    std::cout << match[0] << std::endl; 
    line = match.suffix().str(); 
} 
+0

'm.suffix()STR()'? – suspectus

+0

@suspectus,請參見['match_resulsts :: suffix'](http://www.cplusplus.com/reference/regex/match_results/suffix/)和['match_resulsts :: str'](http://www.cplusplus的.com /參考/正則表達式/的match_results/STR /)。 – falsetru

+0

@suspectus,對不起,我誤解了。你的意思是一個錯字。我修好了它。謝謝你指出。 – falsetru