下划线转驼峰
private static Pattern linePattern = Pattern.compile("[_]\\w");
/**
* 下划线转驼峰
* @param str
* @return
*/
public static String lineToHump(String str) {
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(0).replace("_","").toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
驼峰转下划线
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/**
* 驼峰转下划线
* @param str
* @return
*/
public static String humpToLine(String str) {
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
JSON字符串key键下划线转驼峰
private static Pattern jsonKeyPattern = Pattern.compile("_[\\w]+\":");
/**
* JSON key 从下划线转为驼峰
*
* @param json
* @return
*/
public static String jsonKeyLineToHump(String json) {
Matcher matcher = jsonKeyPattern.matcher(json);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
int index;
StringBuilder builder = new StringBuilder(matcher.group(0));
while ((index = builder.indexOf("_")) != -1) {
String c = String.valueOf(builder.charAt(index+1));
builder.replace(index, index + 2, c.toUpperCase());
}
matcher.appendReplacement(sb, builder.toString());
}
matcher.appendTail(sb);
return sb.toString();
}