Java中驼峰和下划线的互相转换是开发中常见的需求。
以下直接给出转换的代码
package com.yxjc;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws ParseException {
//下划线转驼峰
System.out.println(Test.underline2Camel("yxjc123_com", true));
//驼峰转下划线
System.out.println(Test.camel2Underline("yxjc123Com"));
}
/**
* 下划线转驼峰
* @param line
* @param smallCamel
* @return
*/
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();
}
/**
* 驼峰转下划线
* @param line The source string
* @return The converted string
*/
public static String camel2Underline(String line){
Pattern compile = Pattern.compile("[A-Z]");
Matcher matcher = compile.matcher(line);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
}
在下划线转驼峰方法中有两个参数第一个参数是要转换的字符串,第二个参数是否对转换的字符串进行小写处理。