Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active May 2, 2021 10:18
Show Gist options
  • Save fabiolimace/3f12520b3a01fae371aba91d3a510202 to your computer and use it in GitHub Desktop.
Save fabiolimace/3f12520b3a01fae371aba91d3a510202 to your computer and use it in GitHub Desktop.
Expand character ranges like 0-9, a-z, and A-Z
package your.package;
public class CharacterRange {
/**
* Expands character ranges similar to 0-9, a-z and A-Z.
*
* @param string a string to be expanded
* @return a string
*/
public static String expand(String string) {
StringBuilder buffer = new StringBuilder();
int i = 1;
while (i <= string.length()) {
final char a = string.charAt(i - 1); // previous char
if ((i < string.length() - 1) && (string.charAt(i) == '-')) {
final char b = string.charAt(i + 1); // next char
char[] expanded = expand(a, b);
if (expanded.length != 0) {
i += 2; // skip
buffer.append(expanded);
} else {
buffer.append(a);
}
} else {
buffer.append(a);
}
i++;
}
return buffer.toString();
}
private static char[] expand(char a, char b) {
char[] expanded = expand(a, b, '0', '9'); // digits (0-9)
if (expanded.length == 0) {
expanded = expand(a, b, 'a', 'z'); // lower case letters (a-z)
}
if (expanded.length == 0) {
expanded = expand(a, b, 'A', 'Z'); // upper case letters (A-Z)
}
return expanded;
}
private static char[] expand(char a, char b, char min, char max) {
if ((a > b) || !(a >= min && a <= max && b >= min && b <= max)) {
return new char[0];
}
char[] buffer = new char[(b - a) + 1];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (char) (a + i);
}
return buffer;
}
public static void main(String[] args) {
String[] ranges = { //
"0-9", "a-z", "A-Z", "0-9a-f", "a-z2-7", "0-9a-v", //
"0-9a-hj-kmnp-tv-z", "0-9a-z", "1-9A-HJ-NP-Za-km-z", //
"A-Za-z0-9", "A-Za-z0-9+/", "A-Za-z0-9-_" };
for (int i = 0; i < ranges.length; i++) {
String input = ranges[i];
String output = CharacterRange.expand(ranges[i]);
System.out.println("input: " + input);
System.out.println("output: " + output);
System.out.println();
}
}
}
@fabiolimace
Copy link
Author

Output:

input:  0-9
output: 0123456789

input:  a-z
output: abcdefghijklmnopqrstuvwxyz

input:  A-Z
output: ABCDEFGHIJKLMNOPQRSTUVWXYZ

input:  0-9a-f
output: 0123456789abcdef

input:  a-z2-7
output: abcdefghijklmnopqrstuvwxyz234567

input:  0-9a-v
output: 0123456789abcdefghijklmnopqrstuv

input:  0-9a-hj-kmnp-tv-z
output: 0123456789abcdefghjkmnpqrstvwxyz

input:  0-9a-z
output: 0123456789abcdefghijklmnopqrstuvwxyz

input:  1-9A-HJ-NP-Za-km-z
output: 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz

input:  A-Za-z0-9
output: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

input:  A-Za-z0-9+/
output: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

input:  A-Za-z0-9-_
output: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment