简体   繁体   中英

How to parse numbers from a string using regex

I'm trying to understand why my regex below is failing. I'm trying to retrieve a range of values on both sides of the : but my code always fails to the else . range is coming from a command line arg like this java -jar myprogram.jar -R 50:100 .

Is it failing because I'm passing a string to the matches() and looking for integers?

Here is my code:

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

   if(range.matches("\\d+:\\d+")) {

      String[] numbers = range.split(":")
      rangeResults[0] = Integer.parseInt(numbers[0]);
      rangeResults[1] = Integer.parseInt(numbers[1]);
   } else {
      throw new Exception("Invalid Syntax.");
   }
   return rangeResults;
}   

I would write it like this

private static int[] parseRangeResults(String range) {
    String[] numbers = range.split(":", -2)
    return new int[] {Integer.parseInt(numbers[0]),Integer.parseInt(numbers[1])};
}

If there is no : it will give you an IndexOutOfBoundException: 1

If there is an invalid number like 1abc:234 you will get NumberFormatException: Unable to parse 1abc

The issue is your handling of the output array. String.split removes the delimiter and does not include it in the array. Your numbers will be in numbers[0] and numbers[1] . numbers[2] will throw an exception.

private int[] parseRangeResults(String range) {
   int[] rangeResults = new int[2];
   if(range.matches("\\d+:\\d+")) {   
      String[] numbers = range.split(":")
      rangeResults[0] = Integer.parseInt(numbers[0]);
      rangeResults[1] = Integer.parseInt(numbers[1]);
   } else {
      throw new Exception("Invalid Syntax.");
   }
   return rangeResults;
}

Regex "\\\\d+:\\\\d+" for string "asdf123:456qwerty" will always return true

Use that regex instead

"^\\d+:\\d+$"

Or use exceptions

try{
    Integer.parseInt("asdf");
}catch(NumberFormatException e){
    throw ...;
}

And

try{
    String s1 = p[0];
    String s2 = p[1];
}catch(ArrayIndexOutOfBoundsException e){
    throw ...;
}

PS. Are you sure about numbers[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