2017-02-10 90 views
1

當我嘗試使用某些正則表達式時,出現「分段錯誤」。在這個例子中,第一個正則表達式工作得很好,但第二個生產分段錯誤:分段錯誤C++正則表達式

#include <regex> 
#include <iostream> 

using namespace std; 

void out(const string& s, const string& d,bool b) { cout << s << ", " << d << (b ? "=found" : "=not found") << endl; } 

int 
main() 
{ 
    const auto exp1 = string{"<.*>.*</.*>"}; 
    const auto reg1 = regex{exp1}; 
    const auto data1 = string{"<tag>value</tag>"}; 
    const auto found1 = regex_match(data1, reg1); 
    out(exp1, data1, found1); 

    const auto exp2 = string{"<(.*)>.*</\\1>"}; 

    cout << "About to create the regex!" << endl; 
    const auto reg2 = regex{exp2}; 
    cout << "done." << endl; 

    const auto data2 = string{"<tag>value</tag>"}; 
    const auto found2 = regex_match(data2, reg2); 
    out(exp2, data2, found2); 

    cout << "All done!" << endl; 
} 

我編譯它是這樣的:

g++ -O0 -g -Wall -Wpedantic -std=c++11 try3.cpp -o try3 

當我運行它,我得到這個:

$ ./try3 
<.*>.*</.*>, <tag>value</tag>=found 
About to create the regex! 
Segmentation fault 

我在CentOS運行釋放5.11的libstdC++ - 4.1.2-55.el5

+0

這是編譯regex庫,而不是正則表達式本身就是一個問題。如果圍繞該線投入嘗試/抓住,你可以分辨出是否是這種情況,但它從未被抓到。 – sln

+0

@sln:true,我之前嘗試過使用try語句,但它沒有捕獲任何東西。你(或其他人)是否有變通辦法? –

+0

不確定,但谷歌的問題,它可能是lib版本或編譯時設置了什麼標誌。有人應該通過,知道肯定。 – sln

回答