驼峰与下划线命名相互转换

驼峰命名转换成下划线命名或者下划线命名转换成驼峰命名

package cn.liyy.upload.utiles;
import java.util.regex.Pattern;
public class ConvertName {
    public static String convertName (String name) {
        String result = "";
        if (name != null) {
            if (!Pattern.compile( ".*[_]+.*" ).matcher( name ).matches()) {//是否是下划线命名
                if (!Pattern.compile( ".*[A-Z]+.*" ).matcher( name ).matches()) {//是否包含大写字母
                    return name;
                }
                result = name.replaceAll( "([a-z])([A-Z])", "$1" + "_" + "$2" ).toUpperCase();
            } else {
                for (String s : name.split( "_" )) {
                    result = result + s.substring( 0, 1 ).toUpperCase()+s.substring( 1 ).toLowerCase();
                }
                result=result.substring( 0, 1 ).toLowerCase()+result.substring( 1 );
            }
        } else {
            return null;
        }
        return result;
    }
}

public class ConvertName {
    public static String convertName (String name) {
        String result = "";
        if (name != null) {
            StringBuffer sb = new StringBuffer();
            if (!Pattern.compile( ".*[_]+.*" ).matcher( name ).matches()) {//是否是下划线命名
                if (!Pattern.compile( ".*[A-Z]+.*" ).matcher( name ).matches()) {//是否包含大写字母
                    return name;
                }
                char[] chars = name.toCharArray();
                for (int i = 0; i < chars.length; i++) {
                    if (Character.isUpperCase( chars[i] )) {
                        sb.append( "_" + chars[i] );
                    } else {
                        sb.append( chars[i] );
                    }
                }
                result = sb.toString().toUpperCase();
                if (result.substring( 0, 1 ).equals( "_" )) {//是否以"_"开始
                    result = result.substring( 1 );
                }
            } else {
                if (name.substring( name.length() - 1 ).equals( "_" )) {//结尾是否是"_"
                    name = name.substring( 0, name.length() - 1 );
                }
                name = name.toLowerCase();
                char[] chars = name.toCharArray();
                for (int i = 0; i < chars.length; i++) {
                    if (chars[i] == '_') {
                        sb.append( Character.toUpperCase( chars[i + 1] ) );
                        i++;
                    } else {
                        sb.append( chars[i] );
                    }
                }
                result = sb.toString();
            }
        } else {
            return null;
        }
        return result;
    }
}

自动判断驼峰还是下划线

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值