java中驼峰与下划线的写法互转

笔记下驼峰与下划线互转的工具类:

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Underline2Camel {

 /**
  * 下划线转驼峰法
  * @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 源字符串
  * @return 转换后的字符串
  */

 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.toLowerCase());
   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

另一种写法:

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Underline2Camel {

    /**
     * 下划线转驼峰,简化
     * 比如:(_[a-z]{1})([a-z]{1})   wei_pay_order
     * group(0)表示匹配表达式第0组 即整个匹配  _pa
     * group(1)表示表达式第一组括号匹配的部分 _p
     * group(2)表示表达式第二组括号匹配的部分 a
     */
    public static String underlineToCamel(String underlineName) {
        Matcher matcher = Pattern.compile("(_[a-z]{1})").matcher(underlineName);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String replacement = matcher.group(1);
            matcher.appendReplacement(result, replacement.replace("_", "").toUpperCase());  //把匹配到的内容替换并追加到result
        }
        matcher.appendTail(result);  //把最后一次未匹配到的剩余内容追加到result  比如:"rder"
        return result.toString();
    }

    /**
     * 驼峰法转下划线,简化
     */
    public static String camelToUnderline(String camelName) {
        return camelName.replaceAll("([A-Z]+)", "_$1").toLowerCase();
    }

    public static void main(String[] args){
        String str = "weiPayOrder";
        String underline = camelToUnderline(str);
        System.out.println(underline);
        System.out.println(underlineToCamel(underline));
    }
}

运行结果如下:

wei_pay_order
weiPayOrder

你可能感兴趣的:(java中驼峰与下划线的写法互转)