Home > Software engineering >  Is there option to change string in second argument of replaceAll, accessed by capture group
Is there option to change string in second argument of replaceAll, accessed by capture group

Time:01-08

I write a program replacing String in which words are delimited by '-' or '_' (word1-word2-word3... or word1_word2_word3... or any combination of those), to camel case format: word1Word2Word3...
I wanted to do it like this: str.replaceAll("[-_]([a-zA-Z0-9])", "$1".toUpperCase()); and half of it sorta works: I get resutl of: word1word2word3... - looks like, toUpperCase() didn't have any effect, so my questions are: why is it so and how to make it work - preferably using replaceAll()

  • Sample input: word1_word2_word3
  • Expected output: word1Word2Word3

CodePudding user response:

Use the replaceAll(Function<MatchResult, String>) method of Matcher:

str = Pattern.compile("[-_]([a-zA-Z0-9])")
    .matcher(str)
    .replaceAll(mr -> mr.group(1).toUpperCase());

See live demo showing that:

String str = "word1_word2-word3";
str = Pattern.compile("[-_]([a-zA-Z0-9])")
    .matcher(str)
    .replaceAll(mr -> mr.group(1).toUpperCase());
System.out.println(str);

Outputs:

word1Word2Word3

CodePudding user response:

Here is working solution for your mentioned problem :

public static void main(String[] args) {

        char[] deliminators = {'-', '_'};
        String input = "word1-word2-word3_word1_word2_word3";
        char[] output = "word1-word2-word3_word1_word2_word3".toCharArray();

        int index = 0;
        for (char element : input.toCharArray()) {

            if (ArrayUtils.contains(deliminators, element)) {
                ArrayUtils.remove(output, index);
                index  ;
                output[index] = Character.toUpperCase(output[index]);
                continue;
            }
            index  ;
        }
        output[0] = Character.toUpperCase(output[0]);

        String.valueOf(output).replaceAll("-", "").replaceAll("_", "");
        System.out.println(String.valueOf(output).replaceAll("-", "").replaceAll("_", ""));
    }

Kindly acknowledge , it should work directly for your use-case.

  • Related