混淆它!为什么这个简单的测试用例不起作用?

pha*_*ers 1 java

@Test
public void testCamelCase() {
    String orig="want_to_be_a_camel";
    String camel=orig.replaceAll("_([a-z])", "$1".toUpperCase());
    System.out.println(camel);
    assertEquals("wantToBeACamel", camel);
}
Run Code Online (Sandbox Code Playgroud)

显示"wanttobeacamel"后失败.为什么没有大写字符?

java version "1.6.0_29"
Java(TM) SE Runtime Environment (build 1.6.0_29-b11)
Java HotSpot(TM) 64-Bit Server VM (build 20.4-b02, mixed mode)
Run Code Online (Sandbox Code Playgroud)

========= Post Mortem:

使用简单的replaceAll是一个死胡同.我只是为了教我的孩子编写代码来做这件事......但是对于Jayamohan来说,这是另一种方法.

public String toCamelCase(String str) {
    if (str==null || str.length()==0) {
        return str;
    }
    char[] ar=str.toCharArray();
    int backref=0;
    ar[0]=Character.toLowerCase(ar[0]);
    for (int i=0; i<ar.length; i++) {
        if (ar[i]=='_') {
            ar[i-backref++]=Character.toUpperCase(ar[i+++1]);
        } else {
            ar[i-backref]=ar[i];
        }
    }
    return new String(ar).substring(0,ar.length-backref);
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*ers 6

我认为这是因为"$ 1".toUpperCase()在replaceAll之前运行.由于"$ 1"字面上没有任何大写的字母,所以它就像是"$ 1"一样.然后当replaceAll运行时,下划线后跟小写字母的模式将被小写字母替换.