2013-10-01 59 views
2

使用正則表達式我想匹配這個表達式的子得到的所有子:1 [0] +1無法從字符串在C++中

std::string str = "0011011000001"; 
std::regex rx ("1[0]+1"); 
std::smatch res; 
std::regex_search(str, res, rx); 
for (size_t i=0; i<res.size(); i++) 
std::cout<<res[i]<<std::endl; 

但它返回我只有第一個字符串。 我在做什麼錯?

+0

你在C++ 11模式下使用G ++?該實現目前還不支持Std regexps ... – 6502

回答

1

你應該這樣做來獲取所有子:

while (std::regex_search (str,res,rx)) { 
    std::cout <<res[0] << std::endl; 
    str = res.suffix().str(); 
} 

或者你可以使用std :: regex_iterator得到如下的所有子:

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

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

但它仍然會輸出 '101'當字符串爲「00110101000001」時爲'1000001',因爲第一個匹配消耗部分字符串。如果您想查找所有重疊的匹配項,則需要支持Lookaround Assertion的正則表達式實現。 Python做:

>>> re.findall(r'(?=(1[0]+1))', '00110101000001') 
['101', '101', '1000001'] 

(?= ...) 匹配,如果匹配......未來,但不消耗任何的字符串。這被稱爲前瞻斷言。例如,Isaac(?= Asimov)只有跟隨着'Asimov'纔會匹配'Isaac'。

0

進行匹配非貪婪...

std::regex rx ("(1[0]+1)?");