Skip to content

Instantly share code, notes, and snippets.

@twiddles
Created December 2, 2011 10:52
Show Gist options
  • Save twiddles/1422786 to your computer and use it in GitHub Desktop.
Save twiddles/1422786 to your computer and use it in GitHub Desktop.
sanitize config value
package snippet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Snippet {
public static void main(String[] args) {
String[] examples = new String[] { "configGlossary:poweredByIcon -> CONFIG_GLOSSARY_POWERED_BY_ICON", "124$32SomeSampleString_thatI_have -> SOME_SAMPLE_STRING_THAT_I_HAVE", "myJSP -> MY_JSP" };
for (String s : examples) {
String[] split = s.split(" -> ");
String input = split[0];
String expected = split[1];
String transformed = transform(input);
if (!transformed.equals(expected)) {
System.out.println("not working for: " + input + ", got " + transformed);
} else {
System.out.println(" working for: " + input + ", got " + transformed);
}
}
}
private static String transform(String input) {
input = replaceUnwantedCharacters(input);
input = splitWordsByDashes(input);
input = handleMultipleUpcaseCharacters(input);
return input;
}
private static String handleMultipleUpcaseCharacters(String input) {
Matcher m = Pattern.compile("([A-Z]{2,})").matcher(input);
StringBuffer multipleUpcases = new StringBuffer();
while (m.find()) {
String multipleUpcaseCharacters = m.group(1).toLowerCase();
m.appendReplacement(multipleUpcases, "_" + multipleUpcaseCharacters.substring(0, 1).toUpperCase() + multipleUpcaseCharacters.toLowerCase().substring(1));
}
m.appendTail(multipleUpcases);
return multipleUpcases.toString().toUpperCase();
}
private static String splitWordsByDashes(String input) {
StringBuffer withMoreDashes = new StringBuffer();
Matcher camel = Pattern.compile("([A-Z][a-z_]+)").matcher(input);
while (camel.find()) {
camel.appendReplacement(withMoreDashes, "_" + camel.group(1));
}
camel.appendTail(withMoreDashes);
// remove dash at the beginning if there is one, this might have
// happended if the input starts with an uppercase letter
input = withMoreDashes.toString().replaceFirst("^_", "");
return input;
}
private static String replaceUnwantedCharacters(String input) {
input = input.replaceAll("\\d", "");
input = input.replaceAll("\\$", "");
input = input.replaceAll("\\W", "_");
return input;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment