2017-05-04 123 views
-1

下面是使用正則表達式匹配字符串但不起作用的C++程序。我的操作系統是Ubuntu Linux,編譯器是ubuntu自帶的標準C++編譯器。C++中的正則表達式不起作用。你能解釋爲什麼嗎?

#include <iostream> 
#include <regex> 

using namespace std; 

int main() { 
    const char s[] = "This is a target string"; 
    regex e ("^([0-9a-zA-Z]*).*?"); 
    cmatch matches; 
    if(regex_match(s, matches, e)) { 
     cout << "Match found" << endl; 
     for (int i = 0; i < matches.size(); ++i) { 
      cout << matches[i] << endl; 
     } 
    } 
    return 0; 
} 

在使用克++象下面

g++ -o test test.cpp -std=c++11 

並且運行該程序是與下面輸出

terminate called after throwing an instance of 'std::regex_error' 
    what(): regex_error 
[1] 24898 abort (core dumped) ./test 

圖案工作正常,我試圖在rubular.com失敗編譯.I我希望它打印

Match Found 
This is a target string 
This 

我是在C++中使用正則表達式的新手。請指向正確的方向。

+1

是您的編譯器版本的GCC 4.8? (默認在Ubuntu 14.04中,我相信)。 –

+0

我無法重現,但是您打算在字符串的末尾包含問號嗎?通常情況下,'?'是一個特殊字符,但在這裏它不適用於任何東西,因爲'。*'已經匹配0或更多。因此,我認爲它會被解釋爲匹配文字'',但是,它可能無法很好地定義 – happydave

+1

嘗試:?'G ++ --version'如果版本低於'GCC 4.9'然後正則表達式不起作用。您需要升級編譯器。 – Galik

回答

0

你能使用的try/catch,趕上regex_error和打印e.what()知道excatly出了問題。

順便說一下,它與我的gcc與C++ 11標誌的工作完美

catch (const std::regex_error& e) { 
     std::cout << "regex_error caught: " << e.what() << '\n'; 
     if (e.code() == std::regex_constants::error_brack) { 
      std::cout << "The code was error_brack\n"; 
     } 
    } 
+0

看來,我用C++構造的正則表達式有問題。 – lucifer

+0

我得到這個,當我試圖捕獲錯誤:'regex_error抓:regex_error 代碼爲error_brack' – lucifer

相關問題