好的,所以我正在尝试学习c ++正则表达式,我遇到了一些问题。我查了一下代码,至少对我来说,这是合乎逻辑的。我还使用正则表达式测试器在线测试它,它成功地匹配了我的字符串。前两个(nameParser
和anotherNameParser
)不起作用,但最后一个(sampleParser
)起作用。我真的不明白为什么它没有验证我的字符串。下面我包括了一个屏幕截图:
//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;
}
答案 0 :(得分:5)
//Need the extended or basic because gnu gcc-4.6.1 doesn't fully support c++11 regular expressions (28.13).
尽管存在<regex>
标题,但它在版本4.9之前并不支持所有 。
有时看起来可能会做你想要的,但它基本上没有。
升级到GCC 4.9。
答案 1 :(得分:1)
在GCC 4.9之前未添加对<regex>
的支持。请参阅release notes:
运行时库(libstdc ++)
- 改进了对C ++ 11的支持,包括:
- 支持
<regex>
;