駝峰轉下劃線

魚常躍發表於2020-10-15

駝峰轉下劃線

// An highlighted block
package com.datacvg.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tool {
    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /** 駝峰轉下劃線,效率比上面高 */
    public static String humpToLine2(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static void main(String[] args) {
        String lineToHump = "fiParentNoLeader";
        System.out.println(humpToLine2(lineToHump));// fi_parent_no_leader
    }

}

相關文章