public class RegexTest {

    public static void main(String[] args) {
        System.out.println(underscoreToCamelcase("regex_test"));
        System.out.println(camelcaseToUnderscore("regexTest"));
    }

    /**
     * 下划线转驼峰
     *
     * @param underscore
     * @return
     */
    public static String underscoreToCamelcase(String underscore) {
        Pattern compile = Pattern.compile("_(\\S)");
        Matcher matcher = compile.matcher(underscore);
        return matcher.replaceAll(matchResult -> matchResult.group(1).toUpperCase());
    }

    /**
     * 驼峰转下划线
     *
     * @return
     */
    public static String camelcaseToUnderscore(String variableName) {
        return variableName.replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase();
    }
}
  • 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.

输出结果

regexTest

regex_test