1 自定义代码实现
1.1 驼峰转下划线
// 自定义正则表达式
private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z0-9]");
private String humpToLine(String str) {
Matcher matcher = HUMP_PATTERN.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
1.2 下划线转驼峰
private static final char UNDERLINE = '_';
private String underlineToCamel(String param) {
if (StringUtils.isBlank(param)) {
return "";
}
int len = param.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = Character.toLowerCase(param.charAt(i));
if (c == UNDERLINE) {
if (++i < len) {
sb.append(Character.toUpperCase(param.charAt(i)));
}
} else {
sb.append(c);
}
}
return sb.toString();
}
2 使用 Guava 实现
使用 Guava
的话需要 Maven
项目引入依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
2.1 驼峰转下划线
import com.google.common.base.CaseFormat;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
@Slf4j
public class ConvertLineToHumpTest {
@Test
public void convertLineToHumpTest() {
String resultStr = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "studentName");
log.info(" >>> 驼峰转下划线 : {}", resultStr);
}
}
>>> 驼峰转下划线 : student_name
2.2 下划线转驼峰
import com.google.common.base.CaseFormat;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
@Slf4j
public class ConvertHumpToLineTest {
@Test
public void convertHumpToLineTest() {
String resultStr = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "student_name");
log.info(" >>> 下划线转驼峰 : {}", resultStr);
}
}
>>> 下划线转驼峰 : studentName