简体   繁体   English

通过getline()输入正则表达式无法正常工作

[英]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. 我需要验证一个至少5个字符长的字符串,包含至少一个大写字母,至少一个小写字母,至少一个数字,除了短划线和下划线之外没有其他字符。 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. 但是,在C ++中,这个简单的测试程序将诸如“AasdA”之类的字符串验证为正确的输入。 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. 也许这与getline()存储字符串的方式有关。 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,}$"))) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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