herohuyongtao
herohuyongtao

Reputation: 50697

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?

Upvotes: 1

Views: 2169

Answers (4)

KitsuneYMG
KitsuneYMG

Reputation: 12901

Yeah, I know this will work. I just want to check if we can verify it's indeed a number and at the same time check its range using

Okay... But don't use regex for this task. It's a terrible choice.

#include <iostream>
#include <sstream>
using namespace std;


bool is_number_in_range(string s) {
    istringstream str(s);
    int i; char c;
    str >> i;
    if( str.fail() ) return false;
    return i>=1256 && i<=4350 && str.eof();
}

int main() {
    cout<< is_number_in_range("0") << '\n'<<
        is_number_in_range("1234") << '\n'<<
        is_number_in_range("1256") << '\n'<<
        is_number_in_range("2000") << '\n'<<
        is_number_in_range("4350") << '\n'<<
        is_number_in_range("5000") << '\n'<<
        is_number_in_range("abcd") << '\n'<<
        is_number_in_range("1234.0") << '\n';


    return 0;
}

see it live

Upvotes: 1

Praetorian
Praetorian

Reputation: 109219

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
}

Upvotes: 4

GabiMe
GabiMe

Reputation: 18503

Here is a great site that will give you the answer.

For your example:

(\b(125[6-9]|12[6-9][0-9]|1[3-9][0-9]{2}|[23][0-9]{3}|4[0-2][0-9]{2}|43[0-4][0-9]|4350)\b

Upvotes: 2

npinti
npinti

Reputation: 52185

Using this website, the regex you are after should look like this: ^(125[6-9]|12[6-9][0-9]|1[3-9][0-9]{2}|[23][0-9]{3}|4[0-2][0-9]{2}|43[0-4][0-9]|4350)$.

That being said, I think it is far more readable and maintainable do break it into two steps, first validate the data type and then the range. (What happens when the range shifts? Your entire regex will most likely be made useless).

Upvotes: 3

Related Questions