Undoing CamelCase
Technology June 1st, 2007Here’s a little method I had to write yesterday to split a CamelCase’d word into a string separated by spaces instead (as a part of my Java-based Wiki Bot software).
No frills, just accepts a String such as "CamelCase" and returns "Camel Case". The code uses Java’s regular expressions to split the string on \p{Lu}, which is just regex fancy speak for any unicode upper case letter.
Enjoy.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Simple test case for splitting a CamelCase word.
*
* @author Pål Brattberg
*/
public class Test {
/**
* Split a CamelCase string into a space separated string.
*
* @param inputString
* The string you wish to split.
* @return A string where each upper case letter is separated by a single
* space
*/
public static String unCamelize(final String inputString) {
Pattern p = Pattern.compile("\\p{Lu}");
Matcher m = p.matcher(inputString);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, " " + m.group());
}
m.appendTail(sb);
return sb.toString().trim();
}
public static void main(String[] args) {
String s = "CamelCase";
System.out.printf("%s -> %s", s, unCamelize(s));
}
}
The program outputs “CamelCase -> Camel Case”.
Go to Sun for more on Java regex.
November 8th, 2007 at 7:25 am
Thanks, works ok. One typo: should be “\\p{Lu}”.
I am really bad ad regexps but I had to change the code because I want that continuous uppercase do not get separated so that “CustomerID” become “Customer ID” and not “Customer I D”, same for “ID” becoming “I D”.
So I wrote this, maybe there is a better way…
Pattern p = Pattern.compile(”\\p{Lu}”);
Matcher m = p.matcher(inputString);
StringBuffer sb = new StringBuffer();
int last = 0;
while (m.find()) {
if (m.start() != last + 1)
{
m.appendReplacement(sb,
” ” + m.group());
}
last = m.start();
}
m.appendTail(sb);
return sb.toString().trim();
Bye
Michele