简体   繁体   中英

What is the best way to get a range of results?

I have a program that can be run from the command line with a -R to specify a range of results to return. The -R takes one argument of the form n:n .

Seeing as though n:n could be 1-5 or 10000-500000, what is the best way of get the values on both sides of the : ?

After passing my arg following -R to a method I started doing the following:

private int[] parseRangeResults(String range) {
   int[] rangeResults = new int[2];

   if(!(range.contains(":"))) {
      throw new Exception("Invalid range syntax");
   }

   String[] numbers = range.split(":")
   rangeResults[0] = Integer.parseInt(numbers[0]);
   rangeResults[1] = Integer.parseInt(numbers[2]);

   return rangeResults;
}

But I think this breaks down if someone puts special characters, or 1000:::::5000 , so what is the best way of handling this?

The best way to check the input is with regular expressions if this regex("\\\\d*-\\\\d*") matches, then your output is correct. this is the code for your function

    String regex = "(\\d*):(\\d*)";
    Pattern checkInput = Pattern.compile(regex);

    Matcher matcherInput = checkInput.matcher(range);

    if(matcherInput.matches()){
        rangeResults[1] = Integer.parseInt(matcherInput.group(1));
        rangeResults[2] = Integer.parseInt(matcherInput.group(2));



    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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