好的,所以我想学习C++正则表达式,并且遇到了一些麻烦。我翻阅了代码,至少对我来说,这是合乎逻辑的。我还使用正则表达式在线测试了它,并成功地匹配了我的字符串。前两个(nameParser
和anotherNameParser
)不工作,但最后一个(sampleParser
)。我真的不明白为什么它不验证我的字符串。下面我包括屏幕截图: 为什么我的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;
}
哪个版本克+ +?有些人已经知道他们的正则表达式实现的问题。 – cdhowie 2014-10-31 14:34:08
我怪紫色的背景。 ;)这是评估正则表达式的好地方。 http://regex101.com/这可能会帮助你。 – Wes 2014-10-31 14:38:27
像Wes暗指的那样,当您只需粘贴文本时不要发布图片。另外,你**真的**不应该作为管理员运行。 – Deduplicator 2014-10-31 14:43:31