1.使用 Guava 实现
1.1 引入Guava相关依赖
<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>21.0</version></dependency>
2. 驼峰、下划线互转
2.1 驼峰转下划线
publicstaticvoidmain(String[] args) { StringresultStr=CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "userName"); System.out.println("转换后结果是:"+resultStr); }
输出结果
转换后结果是:user_name
2.2 下划线转驼峰
publicstaticvoidmain(String[] args) { StringresultStr=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "user_name"); System.out.println("转换后结果是:"+resultStr); }
输出结果
转换后结果是:userName
2. 自定义转换
2.1驼峰转下划线
privatestaticfinalPatternTPATTERN=Pattern.compile("[A-Z0-9]"); privateStringteseDemo(Stringstr) { Matchermatcher=TPATTERN.matcher(str); StringBuffersb=newStringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, "_"+matcher.group(0).toLowerCase()); } matcher.appendTail(sb); returnsb.toString(); }