1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import java.util.regex.Matcher; import java.util.regex.Pattern;
public class CasesUtil {
private static final Pattern CAMELCASE_PATTERN = Pattern.compile("[A-Z]"); private static final Pattern UNDERLINE_PATTERN = Pattern.compile("_[a-z]"); private static final char UNDERLINE = '_';
public static String camelCase2UnderlineCase(String camelCase) { Matcher matcher = CAMELCASE_PATTERN.matcher(camelCase); StringBuilder builder = new StringBuilder(camelCase); for (int i = 0; matcher.find(); i++) { builder.replace(matcher.start() + i, matcher.end() + i, UNDERLINE + matcher.group().toLowerCase()); } if (builder.charAt(0) == UNDERLINE) { builder.deleteCharAt(0); } return builder.toString(); }
public static String underlineCase2CamelCase(String underlineCase) { Matcher matcher = UNDERLINE_PATTERN.matcher(underlineCase); StringBuilder builder = new StringBuilder(underlineCase); for (int i = 0; matcher.find(); i++) { builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase()); } if (Character.isUpperCase(builder.charAt(0))) { builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0)))); } return builder.toString(); } }
|