正则表达式 – 用大写替换下划线小写

我想知道是否有一个正则表达式模式,我可以用来将一个下划线和一个小写字母的模式转换为一个大写字母。 我正在尝试从SQL语句为java bean生成字段名。 目前DB列是

load_id,policy_id,policy_number 

但我想要java字段名称

 loadId,policyId,policyNumber 

我试过这个正则表达式小提琴

您可以使用:

 String s = "load_id,policy_id,policy_number"; Pattern p = Pattern.compile( "_([a-zA-Z])" ); Matcher m = p.matcher( s ); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group(1).toUpperCase()); } m.appendTail(sb); System.out.println(sb.toString()); // loadId,policyId,policyNumber 

也许你想使用谷歌番石榴 :

代码

 import static com.google.common.base.CaseFormat.LOWER_CAMEL; import static com.google.common.base.CaseFormat.LOWER_UNDERSCORE; public class Main { public static void main(String[] args) { String str = "load_id,policy_id,policy_number"; for(String columnName : str.split(",")) { System.out.println(LOWER_UNDERSCORE.to(LOWER_CAMEL, columnName)); } } } 

输出

 loadId policyId policyNumber 
 import com.google.common.base.CaseFormat; 
 protected static String replaceDashesWithCamelCasing(String input){ return CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, input); } 

要在regexp级别执行此操作,您必须使用\U打开大写模式,使用\E将其关闭。 下面是一个如何在IntelliJ IDEA find-and-replace对话框中使用此function的示例,该对话框将类字段集转换为JUnit断言(在IDE工具提示中是find-and-replace转换的结果):

在此处输入图像描述