我有一个字符串"B2BNewQuoteProcess"。当我使用Guava将其从驼峰式转换成小写连字符,如下所示:
CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,"B2BNewQuoteProcess");
我得到的是“b2-b-new-quote-process”。
我需要的是“b2b-new-quote-process”...
在Java中该怎么做?
为了防止行首出现-
,请使用以下替代方案而非我的原回答:
(?!^)(?=[A-Z][a-z])
(?=[A-Z][a-z])
替换:-
注意:上面的正则表达式不会将大写字符转换为小写字符;它只是在应该有 -
的位置插入它们。在下面的Java代码中使用 .toLowerCase()
将大写字符转换为小写字符。
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final String regex = "(?=[A-Z][a-z])";
final String string = "B2BNewQuoteProcess";
final String subst = "-";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result.toLowerCase());
}
}
(?=[A-Z][a-z])
正向先行断言,确保其后紧跟一个大写字母和一个小写字母。这被用作位置的断言。替换操作仅在与此断言匹配的位置插入连字符 -
。Java 8及以下版本的方法
使用此方法来转换任何驼峰字符串。您可以选择任何类型的分隔符。
private String camelCaseToLowerHyphen(String s) {
StringBuilder parsedString = new StringBuilder(s.substring(0, 1).toLowerCase());
for (char c : s.substring(1).toCharArray()) {
if (Character.isUpperCase(c)) {
parsedString.append("_").append(Character.toLowerCase(c));
} else {
parsedString.append(c);
}
}
return parsedString.toString().toLowerCase();
}
}
参考代码来自:http://www.java2s.com/example/java-utility-method/string-camel-to-hyphen-index-0.html
驼峰式命名 | 小写连字符 | 应该为 |
---|---|---|
B2BNewQuoteProcess | b2-b-new-quote-process | b2b-new-quote-process |
BaBNewQuoteProcess | ba-b-new-quote-process | |
B2NewQuoteProcess | b2-new-quote-process | |
BABNewQuoteProcess | b-a-b-new-quote-process | bab-new-quote-process |
因此:
修正错误结果的方法是:
String expr = "b2-b-new-quote-process";
expr = Pattern.compile("\\b[a-z]\\d*(-[a-z]\\d*)+\\b")
.matcher(expr).replaceAll(mr ->
mr.group().replace("-", ""));
这个搜索在单词边界(\b
)之间查找一串带有任意数字的字母序列,接着是连字符加上带有任意数字的字母序列的重复。
(?=[A-Z][a-z])
替换为-
,然后将字符串转换为小写。 - ctwheelsB2bNewQuoteProcess
(看起来有点丑)。 - maaartinus