Home > Back-end >  C Regex expressions not working for string and digit validation
C Regex expressions not working for string and digit validation

Time:03-10

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?

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;
}

CodePudding user response:

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] )?.

  • Related