I am trying to getting this output. But failed to missing numbers in separate by this ',' one ?
Input: 1, 2, 3, 4.. 9, 10,13.. 17, 18, 19.. 25
Output: 1 2 3 4 5 6 7 8 9 10 13 14 15 16 17 18 19 20 21 22 23 24 25
Here is a working implementation which does what you need, further explanation below the code:
public static String getCSV(int start, int end) {
List<String> list = IntStream.range(start, end).boxed()
.map(i -> i.toString()).collect(Collectors.toList());
String csv = String.join(" ", list);
return csv;
}
public static void main(String args[])
{
String input = "1, 2, 3, 4.. 9, 10,13.. 17, 18, 19.. 25";
input = input.replaceAll(",\\s*", " ");
Pattern r = Pattern.compile("(\\d+)\\.\\.\\s*(\\d+)");
Matcher m = r.matcher(input);
StringBuffer stringBuffer = new StringBuffer();
while (m.find( )) {
int start = Integer.parseInt(m.group(1));
int end = Integer.parseInt(m.group(2));
m.appendReplacement(stringBuffer, getCSV(start, end+1));
}
System.out.println(stringBuffer);
}
Output:
1 2 3 4 5 6 7 8 9 10 13 14 15 16 17 18 19 20 21 22 23 24 25
This approach uses a regex matcher to identify every pair of numbers which is in ellipsis (e.g. 4.. 9
), and then replaces it with a space separated continuous range from the starting to ending point. Java 8 streams come in handy here, and the getCSV()
method generates a string containing the sequence of numbers from the starting and ending input values. Then, we need only iterate over the entire input, and replace each ellipsis using the helper method.