Using regular expressions to validate a numeric range

后端 未结 11 1585
自闭症患者
自闭症患者 2020-11-21 22:16

My input number is an int. But the input number must be in a range from -2055 to 2055 and I want to check this by using regular expression.

So is there anyway to wri

11条回答
  •  伪装坚强ぢ
    2020-11-21 23:00

    Try with a very simple regex.

    ^([-0][0-1][0-9][0-9][0-9])$|^([-0]20[0-4][0-9])$|^([-0]205[0-5])$
    

    Visual representation

    enter image description here

    It's very simple to understand.

    • group 1 [-0][0-1][0-9][0-9][0-9] will cover [-1999, 1999] values
    • group 2 [-0]20[0-4][0-9] will cover [-2000,-2049] and [2000,2049] values
    • group 3 [-0]205[0-5] will cover [-2050, -2055] and [2050, 2055] values

    String.format("%05d", number) is doing very well done job here?

    Sample code: (Read inline comments for more clarity.)

    int[] numbers = new int[] { -10002, -3000, -2056, -2055, -2000, -1999, -20, 
                                -1,  0, 1, 260, 1999, 2000, 2046, 2055, 2056, 2955, 
                                 3000, 10002, 123456 };
    
    //valid range -2055 to 2055 inclusive
    
    Pattern p = Pattern.compile("^([-0][0-1][0-9][0-9][0-9])$|^([-0]20[0-4][0-9])$|^([-0]205[0-5])$");
    
    for (int number : numbers) {
        String string = String.format("%05d", number);
        Matcher m = p.matcher(string);
    
        if (m.find()) {
            System.out.println(number + " is in range.");
        } else {
            System.out.println(number + " is not in range.");
        }
    }
    

    output:

    -10002 is not in range.
    -3000 is not in range.
    -2056 is not in range.
    -2055 is in range.
    -2000 is in range.
    -1999 is in range.
    -20 is in range.
    -1 is in range.
    0 is in range.
    1 is in range.
    260 is in range.
    1999 is in range.
    2000 is in range.
    2046 is in range.
    2055 is in range.
    2056 is not in range.
    2955 is not in range.
    3000 is not in range.
    10002 is not in range.
    123456 is not in range.
    

提交回复
热议问题