简体   繁体   English

使用正则表达式进行范围检查?

[英]Range checking using regular expressions?

How to perform range checking using regular expressions? 如何使用正则表达式执行范围检查?

Take a 4 -bit number (ie "dddd" ) as an example, how can I check whether it is within given range, say [1256-4350] or not? 以一个4位数字(例如"dddd" )为例,如何检查它是否在给定范围内,例如[1256-4350]

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. 要检查输入是否为4位数字,请使用regex_match ,然后使用std::stoi将字符串转换为整数以检查范围。

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. 正如Jarod42在评论中提到的那样,由于您已经验证了输入为4位数字,因此不必将其转换为整数。 Assuming input is an std::string , this would work too 假设inputstd::string ,这也将工作

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

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)$ . 使用网站,您需要使用的正则表达式应如下所示: ^(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). (当范围变化时会发生什么?您的整个正则表达式很可能会变得无用)。

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

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 现场观看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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