๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ์ƒํ™œ/Java

[JAVA] Case Format ๋ณ€๊ฒฝ (UPPER_CAMEL, LOWER_HYPEN...)

by cocococo331 2022. 3. 22.

google guava ์‚ฌ์šฉ

 

  1. google CaseFormat import
    • import com.google.common.base.CaseFormat;
  2. ์›ํ•˜๋Š” ํฌ๋งท์œผ๋กœ ๋ณ€๊ฒฝ
    String upperCamelVndr = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, "text_test"); //TextTest

  3. ํฌ๋งท ์ข…๋ฅ˜
    //CaseFormat enum ๊ฐ€๋ณด๋ฉด ์ž์„ธํ•˜๊ฒŒ ํ™•์ธ ๊ฐ€๋Šฅ
    
    LOWER_HYPHEN(CharMatcher.is('-'), "-") {
        String normalizeWord(String word) {
            return Ascii.toLowerCase(word);
        }
    
        String convert(CaseFormat format, String s) {
            if (format == LOWER_UNDERSCORE) {
                return s.replace('-', '_');
            } else {
                return format == UPPER_UNDERSCORE ? Ascii.toUpperCase(s.replace('-', '_')) : super.convert(format, s);
            }
        }
    },
    LOWER_UNDERSCORE(CharMatcher.is('_'), "_") {
        String normalizeWord(String word) {
            return Ascii.toLowerCase(word);
        }
    
        String convert(CaseFormat format, String s) {
            if (format == LOWER_HYPHEN) {
                return s.replace('_', '-');
            } else {
                return format == UPPER_UNDERSCORE ? Ascii.toUpperCase(s) : super.convert(format, s);
            }
        }
    },
    LOWER_CAMEL(CharMatcher.inRange('A', 'Z'), "") {
        String normalizeWord(String word) {
            return CaseFormat.firstCharOnlyToUpper(word);
        }
    
        String normalizeFirstWord(String word) {
            return Ascii.toLowerCase(word);
        }
    },
    UPPER_CAMEL(CharMatcher.inRange('A', 'Z'), "") {
        String normalizeWord(String word) {
            return CaseFormat.firstCharOnlyToUpper(word);
        }
    },
    UPPER_UNDERSCORE(CharMatcher.is('_'), "_") {
        String normalizeWord(String word) {
            return Ascii.toUpperCase(word);
        }
    
        String convert(CaseFormat format, String s) {
            if (format == LOWER_HYPHEN) {
                return Ascii.toLowerCase(s.replace('_', '-'));
            } else {
                return format == LOWER_UNDERSCORE ? Ascii.toLowerCase(s) : super.convert(format, s);
            }
        }
    };