Skip to content

Instantly share code, notes, and snippets.

@0guzhan
Created March 8, 2013 09:58
Show Gist options
  • Save 0guzhan/5115436 to your computer and use it in GitHub Desktop.
Save 0guzhan/5115436 to your computer and use it in GitHub Desktop.
From camelCase to UNDER_LINE convention converter. Another regex fun...
package com.blog.oguzhan.charutil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConventionConverter {
public static void main(String[] args) {
String[] output = camelCaseToUnderline(new String[]{"abc","aBc","abC","abCD"});
for (String out : output) {
System.out.println(out);
}
}
public static final String[] camelCaseToUnderline(String[] words) {
if (words != null && words.length > 0) {
String[] outputWords = new String[words.length];
int index = 0;
for (String word : words) {
outputWords[index] = camelCaseToUnderline(word);
index++;
}
return outputWords;
}
else {
throw new IllegalArgumentException("INVALID INPUT");
}
}
public static final String camelCaseToUnderline(String word) {
if (word != null) {
StringBuffer outputWord = new StringBuffer(word.length());
String lowPartPattern = "[a-z]+";
String highPartPattern = "[A-Z][a-z]*";
String camelCasePattern = "[a-z]+([A-Z]{0,1}[a-z]*)*";
Pattern pattern = Pattern.compile(camelCasePattern);
Pattern lowPattern = Pattern.compile(lowPartPattern);
Pattern highPattern = Pattern.compile(highPartPattern);
Matcher matcher = pattern.matcher(word);
while(matcher.find()) {
// find next camel case part
String found = matcher.group();
// grab the low part of the camel case
Matcher lowMatcher = lowPattern.matcher(found);
if(lowMatcher.find()) {
String lowPart = lowMatcher.group();
lowPart = lowPart.toUpperCase();
outputWord.append(lowPart);
}
// grab the high part of the camel case
Matcher highMatcher = highPattern.matcher(found);
while(highMatcher.find()) {
String hightPart = highMatcher.group();
hightPart = hightPart.toUpperCase();
outputWord.append("_");
outputWord.append(hightPart);
}
}
return outputWord.toString();
}
else {
throw new IllegalArgumentException("INVALID INPUT");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment