Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Regex expressions not working for string and digit validation

I’m trying to write 2 functions that validate console input. One for numeric only and another for letter only.

I’m using regex to check the input but they’re returning false for all inputs, even if the expression should match.

I’m really at a loss as to what is wrong here and wondering if anyone can see something I can’t?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m not using the isdigit() function as the input will not be a single char .

Here is the code for each:

bool isLetter(string input){

    bool result;
    regex regex_pattern("^A-Za-z\s");
    result = regex_match(input, regex_pattern);
    cout << "result contains: " << result;
    return result;
}

Code for digit function:

bool isDigit(string input){

    bool result;
    regex regex_pattern("-?[0-9]+.?[0-9]+");
    result = regex_match(input, regex_pattern);
    cout << "result contains : " << result;
    return result;
}

>Solution :

There’s an ancient Chinese proverb that says "If you have a problem and use regexes to solve it, you will have two problems". Indeed, isdigit can only be applied to a single char, but you can use it in a loop:

bool isDigit(std::string input){
    bool result = true;
    for (char c: input)
    {
        result &= isdigit(c);
    }
    return result;
}

Or better yet, use std::all_of from <algorithm> library:

bool isDigit(std::string input){
    return std::all_of(input.begin(), input.end(), ::isdigit);
}

Why your regexes don’t work? This one:
^A-Za-z\s matches literal string A-Za-z (capital A, dash, capital Z, …) and then unknown escape sequence \s. Compiler should warn you that this escape sequence is unspecified.

The other one: -?[0-9]+.?[0-9]+ matches dash (optional), at least 1 digit, optional any character and then again at least 1 digit. It will only work if you have that one other character between, because you used greedy quantifiers.

Correct regexes would be [a-zA-Z]+ for letters (unless you need to make sure there’s a capital letter in the beginning) and -?[0-9]*.?[0-9]* for digits. If you want to not accept numbers like .5, change it to -?[0-9]+.?[0-9]*. If you don’t want to accept 1., make it -?[0-9]*(.[0-9]+)?.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading