【问题标题】:Convert kebab-case to camelCase [closed]将 kebab-case 转换为 camelCase [关闭]
【发布时间】:2022-07-08 20:44:29
【问题描述】:

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

例如:

hello-world

变成

helloWorld

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

【问题讨论】:

  • String#replaceAll 不允许我们根据找到的内容动态生成替换,例如 a 生成 A。但是 Matcher#replaceAll 有接受Function<MatchResult, String> replacer 的重载版本。我们可以使用它来根据当前匹配动态生成替换。所以你的代码看起来像String replaced = Pattern.compile("(?<=[a-z])-([a-z])").matcher(text).replaceAll(matchResult -> matchResult.group(1).toUpperCase());。

标签: java camelcasing kebab-case


【解决方案1】:

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

Wrong: -hello-world => HelloWorld

【讨论】:

    【解决方案2】:

    我会用

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

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

    【讨论】:

      【解决方案3】:
      String kebab = "hello-world";
      String camel = Pattern.compile("-(.)")
          .matcher(kebab)
          .replaceAll(mr -> mr.group(1).toUpperCase());
      

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

      请注意,这只适用于 Java 9+ 并引入了Matcher#replaceAll​(Function<MatchResult, String> replacer)

      【讨论】:

        【解决方案4】:

        您可以轻松适应these answers:

        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;
        }
        

        【讨论】:

          猜你喜欢
          • 2019-12-24
          • 1970-01-01
          • 2019-07-06
          • 2022-07-15
          • 2011-05-08
          • 2013-10-03
          • 1970-01-01
          • 2022-01-23
          • 1970-01-01
          相关资源
          最近更新 更多