2011-06-23 76 views
1

我打算在boost版本1.44中使用back-reference,但這對我不起作用。 這是我的代碼:如何在boost :: regex中使用back-reference

boost::regex_constants::syntax_option_type flags = boost::regex::extended; 
std::string regx="(aaa)bb\1"; 
std::cout << "Expression: \"" << regx << "\"\n"; 
std::string str ="aaabbaaa"; 
boost::regex e(regx,flags); 
if(boost::regex_match(text, what, e))//, boost::match_extra)) 
{ 
    std::cout<<"found"; 
} else 
{ 
    std::cout<<"not found"; 
} 

,這是我的輸出中:

Expression: "(aaa)bbb☺" 
    ** not found ** 
    Press any key to continue . . . 

什麼,我缺少什麼? 當我嘗試std::string regx="(aaa)bb\\1"程序墜毀在boost::regex e(regx,flags); mybe我想念一些國旗?

回答

0

我通過chaning此行

boost::regex_constants::syntax_option_type flags = boost::regex::extended; 

解決這個問題
boost::regex_constants::syntax_option_type flags = boost::regex::bk_vbar; 

andcourse use \\ 這個工作適合我。

感謝

1

"(aaa)bb\\1"。你需要避開反斜線。

+0

什麼是正文?我嘗試'\\ 1',但在boost :: regex e(regx,flags)中崩潰; –

+0

@herzl,我使用'\\ 1'而不是'\ 1',而不是整個單獨的正則表達式。 – Qtax

+0

是的,我做了'std :: string regx =「(aaa)bb \\ 1」'並且崩潰了。 –

1

C++和正則表達式都使用\作爲轉義字符。當您在字符串C++使用它是將其解釋爲八進制字符常量1.你需要加倍逃避1:std::string regx="(aaa)bb\\1";

+0

但是當我嘗試\\ 1它在boost :: regex e(regx,flags)中崩潰; –

1

除了需要逃避你的反斜線:

的boost ::正則表達式的默認設置擴展語法特定no_bk_refs標誌。如果你想使用擴展語法的反向引用,你必須自己解除它:

flags = boost::regex::extended & ~boost::regex::no_bk_refs;