2014-02-09 101 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