Java 不支持正则表达式中的预处理操作。如何解决 Java 中缺少的这个特性?
我想在 Java 中实现一个方法,它与这个GNU sed命令相同:
$ sed 's/\(^\|_\)\([a-z]\)/\U\2/g' <<< first_name
FirstName
sed 调用产生骆驼情况。
为什么不简单地使用老式的字符串操作?
String myStr = "first_name";
myStr = myStr.replace("_", " ");
myStr = StrUtils.Capitalize(myStr);
myStr = mystr.replace(" ", "");
StrUtils 来自http://commons.apache.org/lang/
如果您不想添加 StrUtils,拆分单词并替换第一个字符,只需将小写和大写字母之间的 ASCII 差异(我认为是 32)添加到 char。(或大写函数等...)
如果你试试
public static void main(String[] args) {
System.out.println(toTitleCase("first_name"));
System.out.println(toTitleCase("UPPER_CASE"));
System.out.println(toTitleCase("ßßß_ßßß_dždždž"));
}
public static String toTitleCase(String s) {
StringBuilder sb = new StringBuilder();
for (String word : s.split("_+")) {
sb.append(word.substring(0,1).toUpperCase());
sb.append(word.substring(1).toLowerCase());
}
return sb.toString();
}
印刷
FirstName
UpperCase
SSßßSSßßDŽdždž
我现在用这个:
class camelcase
{
public static void capitalize (String str, StringBuilder builder)
{
int length = str.length();
if (length > 0) {
builder.append (Character.toTitleCase(str.charAt(0)));
if (length > 1)
builder.append (str.substring(1).toLowerCase());
}
}
public static String capitalize (String str)
{
StringBuilder builder = new StringBuilder();
capitalize (str, builder);
return builder.toString();
}
public static void camelcase (String str, StringBuilder builder)
{
for (String word : str.split("[ \\p{Punct}]+"))
capitalize (word, builder);
}
public static String camelcase (String str)
{
StringBuilder builder = new StringBuilder();
camelcase (str, builder);
return builder.toString();
}
public static void main (String[] args)
{
String[] strings = new String[] {
"", "a", "aa", "aa_bb", "aa bb", "aa - bb", "ß", "ßß", "ßß_ßß", "dždž"
};
for (String str : strings)
System.out.println ("'" + str + "' -> '" + camelcase (str) + "'");
}
}