简体   繁体   中英

Regular expression not working correctly through input via getline()

I need to validate a string that is at least 5 characters long, contains at least one upper-case letter, at least one lower-case letter, at least one digit and no other characters except the dash and the underscore. I've tested this in other languages and it apparently works:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z_\-]{5,}$

However, in C++, this simple test program validates strings such as "AasdA" as correct input. I know I am missing something glaringly obvious, but after much research I cannot tell what is wrong. Maybe it's something to do with the way getline() stores strings. Here is my code:

#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,}$"))) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM