Generate a Regular Expression From a Numeric Range

Generate a Regular Expression From a Numeric Range.

Javadoc available at https://www.javatapas.com/docs/javatapas/util/GenerateRegularExpressionFromNumericRange.html


public static String generateRegularExpressionFromNumericRange(int startInteger, int endInteger) throws Exception {

  if(startInteger < 0 || endInteger < 0) {throw new Exception("Negative values not supported");}

  if(startInteger > endInteger) {throw new Exception("Error: Invalid range " + startInteger + " > " + endInteger);}

  List<Integer> ranges = new ArrayList<Integer>();
	ranges.add(startInteger);
  int increment = 1;
  int next = startInteger;
  boolean higher = true;

  while(true) {

    next += increment;

    if(next + increment > endInteger) {
      if(next <= endInteger) {
        ranges.add(next);
      }
      increment /= 10;
      higher = false;
    }
    else if(next % (increment*10) == 0) {
      ranges.add(next);
      increment = higher ? increment*10 : increment/10;
    }

    if(!higher && increment < 10) {
      break;
    }
  }

  ranges.add(endInteger + 1);

  String regex = "(?:";

  for(int i = 0; i < ranges.size() - 1; i++) {
    String startString = String.valueOf(ranges.get(i));
    String endString = String.valueOf(ranges.get(i + 1) - 1);

    for(int j = 0; j < startString.length(); j++) {
      if(startString.charAt(j) == endString.charAt(j)) {
        regex += startString.charAt(j);
      }
      else {
        regex += "[" + startString.charAt(j) + "-" + endString.charAt(j) + "]";
      }
    }
    regex += "|";
  }

  return regex.substring(0, regex.length()-1) + ")";
}