2014-10-31 46 views
0

好的,所以我想學習C++正則表達式,並且遇到了一些麻煩。我翻閱了代碼,至少對我來說,這是合乎邏輯的。我還使用正則表達式在線測試了它,併成功地匹配了我的字符串。前兩個(nameParseranotherNameParser)不工作,但最後一個(sampleParser)。我真的不明白爲什麼它不驗證我的字符串。下面我包括屏幕截圖: Screenshot showing output爲什麼我的C++正則表達式不起作用?

//http://rextester.com/tester 
//compile with g++ -std=gnu++11 main.cpp -o main 
#include <iostream> 
#include <regex> 
using namespace std; 

/* * (nameParser) 
* Beginning at the front of the string, any set of character followed by at least one or more spaces 
* followed by any set of characters with exactly one preceding dot, 
* then followed by at least one or more spaces followed by any set of characters and end of string 
*/ 

//Need the extended or basic because any version less than 4.9 doesn't fully support c++11 regular expressions (28.13). 
//The error is because creating a regex by default uses ECMAScript syntax for the expression, which doesn't support brackets. 
const regex nameParser("^[a-zA-Z]+\\s+[a-zA-Z]\\.{1}\\s+[a-zA-Z]+$",regex::extended); 
const regex anotherNameParser("[a-zA-Z]+",regex::extended); 
const regex sampleParser("(abc)"); 

int main() { 
    //simple regex testing 
    string name = "bob R. Santiago"; 
    if(regex_match(name, nameParser)) { 
     cout << "name is valid!" << endl; 
    } else cout << "Error in valdiating name!" << endl; 

    string anotherName = "Bobo"; 
    if(regex_match(anotherName, anotherNameParser)) { 
      cout << "name is valid!" << endl; 
    } else cout << "Error in valdiating name!" << endl; 

    string sample = "abc"; 
    if(regex_match(sample, sampleParser)) { 
      cout << "name is valid!" << endl; 
    } else cout << "Error in valdiating name!" << endl; 

    return 0; 
} 
+4

哪個版本克+ +?有些人已經知道他們的正則表達式實現的問題。 – cdhowie 2014-10-31 14:34:08

+1

我怪紫色的背景。 ;)這是評估正則表達式的好地方。 http://regex101.com/這可能會幫助你。 – Wes 2014-10-31 14:38:27

+1

像Wes暗指的那樣,當您只需粘貼文本時不要發佈圖片。另外,你**真的**不應該作爲管理員運行。 – Deduplicator 2014-10-31 14:43:31

回答

5
//Need the extended or basic because gnu gcc-4.6.1 doesn't fully support c++11 regular expressions (28.13). 

它不支持他們在所有直到4.9版本,儘管<regex>報頭的存在。

有時它可能會做你想做的事,但它基本上沒有。

升級到GCC 4.9。

1

支持<regex>直到GCC 4.9才被添加。看到release notes

運行時庫(的libstdC++)

  • 爲C++ 11改進的支持,包括:
    • <regex>支持;
相關問題