Search code examples
javaregexcapturing-group

replace all captured groups


I need to transform something like: "foo_bar_baz_2" to "fooBarBaz2"

I'm trying to use this Pattern:

Pattern pattern = Pattern.compile("_([a-z])");
Matcher matcher = pattern.matcher("foo_bar_baz_2");

Is it possible to use matcher to replace the first captured group (the letter after the '_') with the captured group in upper case?


Solution

  • You can use appendReplacement/appendTail methods of the matcher like this:

    Pattern pattern = Pattern.compile("_([a-z0-9])");
    Matcher matcher = pattern.matcher("foo_bar_baz_2");
    
    StringBuffer stringBuffer = new StringBuffer();
    while(matcher.find()) {
        matcher.appendReplacement(stringBuffer, matcher.group(1).toUpperCase());
    }
    matcher.appendTail(stringBuffer);
    
    System.out.println(stringBuffer.toString());