繁体   English   中英

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

[英]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.

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