方式一:
/**
* 蛇形命名 转 驼峰
* @param str 待转换的蛇形命名字符串
* @return 转换后的驼峰式命名
*/
public static String camelize(String str){
if(isBlank(str))
return str;
Pattern pattern = Pattern.compile("(.*)_(\\w)(.*)");
Matcher matcher = pattern.matcher(str);
if(matcher.find()){
return camelize(matcher.group(1) + matcher.group(2).toUpperCase() + matcher.group(3));
}else{
return str;
}
}
/**
* 驼峰命名 转 蛇形命名
* @param camelCaseStr 驼峰式命名
* @return 转换后的蛇形命名
*/
public static String decamelize(String camelCaseStr){
return isBlank(camelCaseStr) ? camelCaseStr : camelCaseStr.replaceAll("[A-Z]", "_$0").toLowerCase();
}
/**
* 字符串是否为空 spring工程直接使用StringUtils中的该方法即可
* @param cs 待检查的字符串
* @return 空:true; 非空:false
*/
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
方式二
//蛇形转驼峰
public String snake_case2camalCase(String selected){
selected = selected.replaceAll("_([A-Z])", "$1");
int i = -32;
for(char c = 'a'; c <= 'z'; ++c) {
selected = selected.replaceAll("_" + c, String.valueOf((char)(c + i)));
}
return selected;
}
//驼峰转蛇形
public String camalCase2snake_case(String selected){
selected = selected.replaceAll("[A-Z]", "_$0");
selected = selected.toLowerCase();
if (selected.charAt(0) == '_') {
selected = selected.substring(1);
}
return selected;
}