Beispiel #1
0
  /**
   * Provides a "smart" integer parsing routine that allows (decimal) numbers in string form with
   * all kind of trailing characters to be parsed into an integer. Some trailing characters are
   * understood as being part of the number, like "k" to denote a value in thousands, or "m" to
   * denote a value in millions.
   *
   * @param aText the text to parse into an integer value, cannot be <code>null</code>;
   * @param aUnitDefinition the unit definition for "k" and "M" characters, should be either SI
   *     (units of 1000) or BINARY (units of 1024);
   * @param aDefault the default value to return in case the given text couldn't be parsed into a
   *     valid number.
   * @return the integer value part of the given text, or the given default value if the text
   *     couldn't be parsed.
   */
  public static int smartParseInt(
      final String aText, final UnitDefinition aUnitDefinition, final int aDefault) {
    // Avoid NPEs when given a null argument; also when an empty
    // string is given, we can be fairly quick in our conclusion...
    if ((aText == null) || aText.trim().isEmpty()) {
      return aDefault;
    }

    final Matcher matcher = SMART_INT_PATTERN.matcher(aText);
    if (matcher.matches()) {
      final String number = matcher.group(1);
      final String unit = matcher.group(2);

      int result = Integer.parseInt(number);
      if (unit != null) {
        result *= parseUnit(unit, aUnitDefinition);
      }
      return result;
    }
    return aDefault;
  }