[英]Regular expression not working correctly through input via getline()
我需要驗證一個至少5個字符長的字符串,包含至少一個大寫字母,至少一個小寫字母,至少一個數字,除了短划線和下划線之外沒有其他字符。 我用其他語言對此進行了測試,它顯然有效:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z_\-]{5,}$
但是,在C ++中,這個簡單的測試程序將諸如“AasdA”之類的字符串驗證為正確的輸入。 我知道我錯過了一些明顯的東西,但經過大量的研究我無法分辨出什么是錯的。 也許這與getline()存儲字符串的方式有關。 這是我的代碼:
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
string test;
do {
cout << "Test: ";
getline(cin, test);
if (regex_match(test, regex("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z_\-]{5,}$"))) {
cout << "True." << endl;
} else {
cout << "False." << endl;
}
} while (test != "");
return 0;
}
您需要將字符串常量中的反斜杠加倍:
if (regex_match(test, regex("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z_\\-]{5,}$"))) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.