目录
一、使用Guava库
Guava库中的CaseFormat类提供了转换不同命名风格的方法。
pom.xml文件中添加如下依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
1.1 从驼峰转换到下划线
import com.google.common.base.CaseFormat;
public class CaseConverter {
public static void main(String[] args) {
String camelCase = "camelCaseExample";
String snakeCase = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, camelCase);
System.out.println(snakeCase); // 输出: camel_case_example
}
}
2..2 从下划线转换到驼峰
import com.google.common.base.CaseFormat;
public class CaseConverter {
public static void main(String[] args) {
String snakeCase = "camel_case_example";
String camelCase = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, snakeCase);
System.out.println(camelCase); // 输出: camelCaseExample
}
}
二、使用Apache Commons Lang库
Apache Commons Lang库中的StringUtils类可以结合正则表达式使用来进行转换。