Added new convertToUnderscore method.

This commit is contained in:
2014-11-01 13:27:09 +01:00
parent 9a8efc403e
commit 032a4ce087
2 changed files with 65 additions and 4 deletions

View File

@@ -429,6 +429,44 @@ public final class StringTools {
return upcaseFirst(word);
}
/**
* Converts a camelCase to a more human form, with spaces.
* E.g. 'Camel Case'.
*
* @param word Word to convert to a readable String
* @return Readable String representation of input word
*/
public static String convertToUnderscore(final String word) {
Pattern pattern = Pattern.compile("([A-Z]|[a-z])[a-z]*");
List<String> tokens = new ArrayList<>();
Matcher matcher = pattern.matcher(word);
String acronym = "";
while (matcher.find()) {
String found = matcher.group();
if (found.matches("^[A-Z]$")) {
acronym += found;
} else {
if (acronym.length() > 0) {
//we have an acronym to add before we continue
tokens.add(acronym);
acronym = "";
}
tokens.add(found);
}
}
if (acronym.length() > 0) {
tokens.add(acronym);
}
if (!tokens.isEmpty()) {
return concatFields(tokens, "-").toLowerCase();
}
return word.toLowerCase();
}
/**
* Takes a string and returns it with the first character
* converted to uppercase.