Last active
May 2, 2021 10:18
-
-
Save fabiolimace/3f12520b3a01fae371aba91d3a510202 to your computer and use it in GitHub Desktop.
Expand character ranges like 0-9, a-z, and A-Z
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: