2013-11-25 58 views
0

我測試了正則表達式[BCGRYWbcgryw]{4}\[\d\]site,它似乎確定找到匹配在以下BBCC [0] .GGRY [0] .WWWW [SOLN]。它與BBCC [0]GGRY [0]regex_match沒有找到任何匹配

但是,當我試圖編碼和調試該匹配時,sm值保持空白。

regex r("[BCGRYWbcgryw]{4}\\[\\d\\]"); 
string line; in >> line; 
smatch sm; 
regex_match(line, sm, r, regex_constants::match_any); 
copy(boost::begin(sm), boost::end(sm), ostream_iterator<smatch::value_type>(cout, ", ")); 

我在哪裏錯了?

+2

哪個編譯器?上次我檢查GCC不支持C++ 11正則表達式。 –

+2

自10月起支持:http://gcc.gnu.org/ – BoBTFish

+0

我曾經用VS'2012 – alexbuisson

回答

1

如果你不想匹配整個輸入序列然後使用std::regex_searchstd::regex_match

#include <iostream> 
#include <regex> 
#include <iterator> 
#include <algorithm> 

int main() 
{ 
    using namespace std; 
    regex r(R"([BCGRYWbcgryw]{4}\[\d\])"); 
    string line = "BBCC[0].GGRY[0].WWWW[soln]"; 
    smatch sm; 
    regex_search(line, sm, r, regex_constants::match_any); 
    copy(std::begin(sm), std::end(sm), ostream_iterator<smatch::value_type>(cout, ", ")); 
    cout << endl; 
} 

注:這也使用原始字符串來簡化正則表達式。

0

我終於搞定了,用()定義了一個捕獲組,我用regex_iterator找到了匹配模式的所有子串。

std::regex rstd("(\\[[0-9]\\]\.[BCGRYWbcgryw]{4})"); 
std::sregex_iterator stIterstd(line.begin(), line.end(), rstd); 
std::sregex_iterator endIterstd; 

for (stIterstd; stIterstd != endIterstd; ++stIterstd) 
{ 
    cout << " Whole string " << (*stIterstd)[0] << endl; 
    cout << " First sub-group " << (*stIterstd)[1] << endl; 
} 

輸出是:

Whole string [0].GGRY 
First sub-group [0].GGRY 
Whole string [0].WWWW 
First sub-group [0].WWWW