驼峰命名和下划线命名互相转化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>
* 驼峰命名和下划线命名互转
* </p>
*
* @package: com.xkcoding
* @description: 驼峰命名和下划线命名互转
* @author: yangkai.shen
* @date: Created in 2018/1/11 上午9:49
* @copyright: Copyright (c) 2018
* @version: 0.0.1
* @modified: yangkai.shen
*/
public class CasesUtil {
private static final Pattern CAMELCASE_PATTERN = Pattern.compile("[A-Z]");
private static final Pattern UNDERLINE_PATTERN = Pattern.compile("_[a-z]");
private static final char UNDERLINE = '_';
/**
* 驼峰命名(形如:UserInfo)转化为下划线命名(user_info)
*
* @param camelCase 驼峰格式的字符串
* @return 下划线形式的字符串
*/
public static String camelCase2UnderlineCase(String camelCase) {
Matcher matcher = CAMELCASE_PATTERN.matcher(camelCase);
StringBuilder builder = new StringBuilder(camelCase);
for (int i = 0; matcher.find(); i++) {
builder.replace(matcher.start() + i, matcher.end() + i, UNDERLINE + matcher.group().toLowerCase());
}
if (builder.charAt(0) == UNDERLINE) {
builder.deleteCharAt(0);
}
return builder.toString();
}
/**
* 下划线命名(user_info)转化为驼峰命名(形如:userInfo)
*
* @param underlineCase 下划线形式的字符串
* @return 驼峰格式的字符串
*/
public static String underlineCase2CamelCase(String underlineCase) {
Matcher matcher = UNDERLINE_PATTERN.matcher(underlineCase);
StringBuilder builder = new StringBuilder(underlineCase);
for (int i = 0; matcher.find(); i++) {
builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
}
if (Character.isUpperCase(builder.charAt(0))) {
builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
}
return builder.toString();
}
}
o(╯□╰)o我只要一毛钱的鼓励~~