好的,所以我想學習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