Search code examples
c++regexc++11range-checking

Range checking using regular expressions?


How to perform range checking using regular expressions?

Take a 4-bit number (i.e. "dddd") as an example, how can I check whether it is within given range, say [1256-4350] or not?


Solution

  • To check whether the input is a 4 digit number use regex_match, and then convert the string to an integer using std::stoi to check the range.

    std::regex expr(R"(\d{4})");
    
    if(std::regex_match(input, expr)) {
        int num = std::stoi(input);
    
        if(num >= 1256 && num <= 4350) {
            // input is within range
        }
    }   
    

    As Jarod42 mentions in the comments, since you've already validated the input is a 4 digit number, it's not necessary to convert it to an integer. Assuming input is an std::string, this would work too

    if(input >= "1256" && input <= "4350") {
        // input is within range
    }