下面是使用正則表達式匹配字符串但不起作用的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++中使用正則表達式的新手。請指向正確的方向。
是您的編譯器版本的GCC 4.8? (默認在Ubuntu 14.04中,我相信)。 –
我無法重現,但是您打算在字符串的末尾包含問號嗎?通常情況下,'?'是一個特殊字符,但在這裏它不適用於任何東西,因爲'。*'已經匹配0或更多。因此,我認爲它會被解釋爲匹配文字'',但是,它可能無法很好地定義 – happydave
嘗試:?'G ++ --version'如果版本低於'GCC 4.9'然後正則表達式不起作用。您需要升級編譯器。 – Galik