前言
在實際項目開發(fā)中,會碰到這樣的問題,數(shù)據(jù)庫表結構設計好了,可實體類還沒相應地弄出來。實體類的屬性命名方法一般是駝峰法,而數(shù)據(jù)庫中的表字段命名方法用的是下劃線法。如果表的字段非常多,我們根據(jù)設計好的數(shù)據(jù)庫字段再手動敲寫一遍駝峰法的屬性,這有點費時了。如何迅速地把數(shù)據(jù)庫中的表字段變成我們所需要的駝峰式的屬性呢?
解決方法有二,一是通過文本編輯工具,如EditPlus,Notepad++等,利用它們攜帶的正則替換功能來迅速實現(xiàn);二是通過自己編寫工具類來實現(xiàn)。至于第一種方法操作技巧,不在這邊贅述。
第二種方法如下:
以下是自己編寫的工具類的代碼:
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
59
60
61
62
63
64
65
|
package day0704; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 駝峰法-下劃線互轉(zhuǎn) * @author cshaper * @since 2015.07.04 * @version 1.0.0 */ public class Underline2Camel { /** * 下劃線轉(zhuǎn)駝峰法 * @param line 源字符串 * @param smallCamel 大小駝峰,是否為小駝峰 * @return 轉(zhuǎn)換后的字符串 */ public static String underline2Camel(String line, boolean smallCamel){ if (line== null || "" .equals(line)){ return "" ; } StringBuffer sb= new StringBuffer(); Pattern pattern=Pattern.compile( "([A-Za-z\\d]+)(_)?" ); Matcher matcher=pattern.matcher(line); while (matcher.find()){ String word=matcher.group(); sb.append(smallCamel&&matcher.start()== 0 ?Character.toLowerCase(word.charAt( 0 )):Character.toUpperCase(word.charAt( 0 ))); int index=word.lastIndexOf( '_' ); if (index> 0 ){ sb.append(word.substring( 1 , index).toLowerCase()); } else { sb.append(word.substring( 1 ).toLowerCase()); } } return sb.toString(); } /** * 駝峰法轉(zhuǎn)下劃線 * @param line 源字符串 * @return 轉(zhuǎn)換后的字符串 */ public static String camel2Underline(String line){ if (line== null || "" .equals(line)){ return "" ; } line=String.valueOf(line.charAt( 0 )).toUpperCase().concat(line.substring( 1 )); StringBuffer sb= new StringBuffer(); Pattern pattern=Pattern.compile( "[A-Z]([a-z\\d]+)?" ); Matcher matcher=pattern.matcher(line); while (matcher.find()){ String word=matcher.group(); sb.append(word.toUpperCase()); sb.append(matcher.end()==line.length()? "" : "_" ); } return sb.toString(); } public static void main(String[] args) { String line= "I_HAVE_AN_IPANG3_PIG" ; String camel=underline2Camel(line, true ); System.out.println(camel); System.out.println(camel2Underline(camel)); } } |
運行結果如下:
iHaveAnIpang3Pig
I_HAVE_AN_IPANG3_PIG
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家學習或者使用Java能有一定的幫助,如果有疑問大家可以留言交流。
原文鏈接:http://www.cnblogs.com/javasharp/p/4622413.html