字符串转为驼峰格式 构建工具类
package com.yt.common.util;
import com.yt.common.dto.NameCode;
import com.yt.exam.enums.ZyEnum;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexUtils {
private static Pattern UNDERLINE_PATTERN = Pattern.compile("_([a-z])");
public static void main(String[] args) {
List<NameCode> nameCode = ZyEnum.getfield();
for (int i = 0; i <nameCode.size() ; i++) {
System.out.println(underlineToHump(nameCode.get(i).getField()));
}
}
public static String underlineToHump (String str){
//正则匹配下划线及后一个字符,删除下划线并将匹配的字符转成大写
Matcher matcher = UNDERLINE_PATTERN.matcher(str);
StringBuffer sb = new StringBuffer(str);
if (matcher.find()) {
sb = new StringBuffer();
//将当前匹配的子串替换成指定字符串,并且将替换后的子串及之前到上次匹配的子串之后的字符串添加到StringBuffer对象中
//正则之前的字符和被替换的字符
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
//把之后的字符串也添加到StringBuffer对象中
matcher.appendTail(sb);
} else {
//去除除字母之外的前面带的下划线
return sb.toString().replaceAll("_", "");
}
return underlineToHump(sb.toString());
}
}
补充
Java还可以实现字符串驼峰格式与下换线格式的转换
下面是实现代码
package yang.demo.justwrite;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VariableNameConversion {
private static Pattern humpPattern = Pattern.compile("[A-Z]");
public static void main(String[] args) {
System.out.println(lowerLineToHump("NAME_AND_addREsS"));
System.out.println(capitalizeTheFirstLetter("nAMe"));
System.out.println(humpToLowerLine("nameAndAddress"));
}
public static String lowerLineToHump(String lowerLineAndUppercaseStr) {
//拆分成数组
String[] eachStr = lowerLineAndUppercaseStr.split("_");
StringBuilder resStr = new StringBuilder();
String firstStr = "";
String tempStr = "";
for (int i = 0; i < eachStr.length; i++) {
//第一个数组全部小写
if (i == 0) {
firstStr = eachStr[0].toLowerCase();
resStr.append(firstStr);
} else {
//以后的数组首字母大写
tempStr = capitalizeTheFirstLetter(eachStr[i]);
resStr.append(tempStr);
}
}
return resStr.toString();
}
public static String capitalizeTheFirstLetter(String str) {
char firstChar = str.toUpperCase().charAt(0);
String nextStr = str.toLowerCase().substring(1);
return firstChar + nextStr;
}
public static String humpToLowerLine(String humpStr, boolean ... defaultUppercaseAndTrueLowercase) {
Matcher matcher = humpPattern.matcher(humpStr);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
//如果第二个形参为true 转为大写
if (defaultUppercaseAndTrueLowercase.length>=1 && defaultUppercaseAndTrueLowercase[0]){
return sb.toString().toUpperCase();
}
return sb.toString();
}
}
输出结果
nameAndAddress
Name
name_and_address
到此这篇关于Java实现字符串转为驼峰格式的方法详解的文章就介绍到这了,更多相关Java字符串转驼峰格式内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!