2014-10-31 47 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>支持;
相关问题