0

我正在寻找一个方法中的简单返回,该方法可以转换任何使用 kebab-case 并将其转换为 camelCase。

例如:

hello-world

成为

helloWorld

我正在尝试使用.replaceAll(),但似乎无法正确使用!

4

4 回答 4

1
String kebab = "hello-world";
String camel = Pattern.compile("-(.)")
    .matcher(kebab)
    .replaceAll(mr -> mr.group(1).toUpperCase());

它将连字符后的字符转换为大写。

于 2022-02-03T15:57:27.037 回答
1

只需找到-的索引,然后将下一个字符放入UpperCase(),然后删除(-)。您需要检查是否有多个 (-) 并检查字符串在句子的开头是否没有 (-),因为您不想要这个结果:

Wrong: -hello-world => HelloWorld
于 2022-02-03T15:33:19.117 回答
1

我会用

String kebab = "hello-world";
String camel = Pattern.compile("-([a-z])")
    .matcher(kebab)
    .replaceAll(mr -> mr.group(1).toUpperCase());

(?<=[a-z])如果您只想对小写字母之后的破折号而不是破折号后跟小写字母的所有实例执行此操作,您还可以在 Pshemo 的评论中包含破折号之前的lookbehind,但假设您的输入格式正确kebab-case 字符串,这可能不是必需的。这完全取决于您希望如何处理“-hello-world”或“HI-there”或“top10-answers”。

于 2022-02-03T17:45:32.957 回答
0

您可以轻松调整这些答案

public String toCamel(String sentence) {
    sentence = sentence.toLowerCase();
    String[] words = sentence.split("-");
    String camelCase= words[0];
    for(int i=1; i<words.length; i++){
        camelCase += words[i].substring(0,1).toUpperCase() + words[i].substring(1);
    }
    return camelCase;
}
于 2022-02-03T15:45:01.277 回答