1

I'm looking for a simple return inside a method that converts any use of kebab-case and turns it into camelCase.

For example:

hello-world

Becomes

helloWorld

I'm trying to use .replaceAll() but I can't seem to get it right!

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Venom
  • 11
  • 1
  • 3
  • ***String#replaceAll*** doesn't let us generate dynamically replacement based on what was found, like for `a` generate `A`. But ***Matcher#replaceAll*** has overloaded version which accepts `Function replacer`. We can use it like to dynamically generate replacement based on current match. So your code can look like `String replaced = Pattern.compile("(?<=[a-z])-([a-z])").matcher(text).replaceAll(matchResult -> matchResult.group(1).toUpperCase());`. – Pshemo Feb 03 '22 at 15:44

4 Answers4

4

I would use

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

You can also include a lookbehind of (?<=[a-z]) before the dash as in Pshemo's comment, if you want to only do it for dashes that come after lowercase letters instead of all instances of a dash followed by a lowercase letter, but assuming your inputs are well-formed kebab-case strings, that may not be necessary. It all depends on how you would like "-hello-world" or "HI-there" or "top10-answers" to be handled.

Note that this only works with Java 9+ with the introduction of Matcher#replaceAll​(Function<MatchResult, String> replacer)

Dexter Legaspi
  • 3,192
  • 1
  • 35
  • 26
David Conrad
  • 15,432
  • 2
  • 42
  • 54
3
String kebab = "hello-world";
String camel = Pattern.compile("-(.)")
    .matcher(kebab)
    .replaceAll(mr -> mr.group(1).toUpperCase());

It takes the char after the hyphen and turns it to upper-case.

Note that this only works with Java 9+ with the introduction of Matcher#replaceAll​(Function<MatchResult, String> replacer)

Dexter Legaspi
  • 3,192
  • 1
  • 35
  • 26
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

Just find the index of the - and then put the next char toUpperCase(), then remove the (-). You need to check if have more than one (-) and also check if the string don't have a (-) at the start of the sentence because u don't want this result:

Wrong: -hello-world => HelloWorld
Alberto Linde
  • 75
  • 1
  • 5
0

You can easily adapt 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;
}
PaoloJ42
  • 115
  • 9