如何将java中的camel case字符串转换为下划线,保留一些大写字母?我在这个代码中使用:
String inputString = "Hi How areYouToday";
String result = inputString.replaceAll("([a-z])([A-Z]+)", "$1_$2");
我可以在Hi How are_You_Today
中转换inputString,但是,我需要得到Hi How are_you_today
。
请注意,只有转换的部分才会更改为小写版本。
您可以根据正则表达式找到的内容使用Matcher#appendReplacement并传递动态替换。
我也改变了你的正则表达式,不在匹配中包含小写部分,但只接受以小写字符开头的大写字符。更多信息:http://www.regular-expressions.info/lookaround.html
String text = "Hi How areYouToday";
Matcher m = Pattern.compile("(?<=[a-z])[A-Z]").matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "_"+m.group().toLowerCase());
}
m.appendTail(sb);
System.out.println(sb.toString()); //Hi How are_you_today
或者从Java 9开始
Matcher m = Pattern.compile("(?<=[a-z])[A-Z]").matcher(text);
String result = m.replaceAll(match -> "_" + match.group().toLowerCase());
因为构造
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb, /*replacement for each match*/);
}
m.appendTail(sb);
String result = sb.toString();
被包裹在Matcher#replaceAll(Function replacer)所以它可以用作
String result = m.replaceAll( (MatchResult match) -> /*replacement for each match*/ );
使用substring或split()将inputtring分割为2,并在单个字符串上使用replace all