java 将大写字段全部改为小写并增加下划线

前言

因为一些原因,需要使用到mybatsPlus 数据库字段的驼峰,必须是下划线,实体类里则可以使用驼峰命名
贴代码

/**
 * Create by wanghongliang
 * 2021/6/16 10:15
 **/

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

/**
 * TODO
 *
 * @author wanghongliang
 * @version 1.0
 * @desc
 * @date 2021/6/16 10:15
 */
public class AzTest {
    public static void main(String[] args) {
        readStream();
//        System.out.println(upperCharToUnderLine("autoGenSerialNumFormat"));
    }

    public static String readStream() {
        Path filePath = Paths.get("C:/Users/Administrator/Desktop", "item_test.txt");
        try (Stream lines = Files.lines(filePath)) {
            lines.forEach(E ->
                    System.out.println(upperCharToUnderLine(E.toString()))
            );
//            lines.forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();//只是测试用例,生产环境下不要这样做异常处理

        }
        return "";
    }

    public static String upperCharToUnderLine(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
//            System.out.println(builder.toString());
//            System.out.println("mc.start():" + mc.start() + ", i: " + i);
//            System.out.println("mc.end():" + mc.start() + ", i: " + i);
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }

        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }
}

-----------------------------------------

以上代码会将大写字母替换成小写并增加下划线
autoGenSerialNumFormat
auto_gen_serial_num_format

posted @ 2021-06-16 11:13  darling331  阅读(954)  评论(0编辑  收藏  举报