Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - replace underscore lowercase with uppercase

Tags:

java

regex

I've wondering is there a regex pattern that i could use to convert a pattern which is an underscore and a lowercase letter into an uppercase letter. I'm trying to generate fieldnames for a java bean from a SQL statement. At the moment the DB columns are

load_id,policy_id,policy_number

but i would like to the java field names to be

loadId,policyId,policyNumber

I've tried with this regex fiddle

like image 338
emeraldjava Avatar asked Mar 31 '14 14:03

emeraldjava


2 Answers

You can use:

String s = "load_id,policy_id,policy_number";
Pattern p = Pattern.compile( "_([a-zA-Z])" );
Matcher m = p.matcher( s );
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, m.group(1).toUpperCase());
}
m.appendTail(sb);
System.out.println(sb.toString()); // loadId,policyId,policyNumber
like image 192
anubhava Avatar answered Nov 05 '22 22:11

anubhava


Maybe you want to use Google Guava:

Code:

import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.LOWER_UNDERSCORE;

public class Main {
    public static void main(String[] args) {
        String str = "load_id,policy_id,policy_number";
        for(String columnName : str.split(",")) {
            System.out.println(LOWER_UNDERSCORE.to(LOWER_CAMEL, columnName));
        }
    }
}

Output:

loadId
policyId
policyNumber
like image 38
Paul Vargas Avatar answered Nov 05 '22 23:11

Paul Vargas