Programing

Java에서 CamelCase를 camel_case로 변환하는 정규식

lottogame 2020. 10. 28. 07:37
반응형

Java에서 CamelCase를 camel_case로 변환하는 정규식


원하는 출력이 같은 문자열 정규식 사용하여 변환 제공되지 않는 이유 이해 FooBarFoo_Bar대신주는를 Foo_Bar_. String.substring으로 뭔가를 할 수도 substring(0, string.length() - 2)있고 마지막 문자를 대체 할 수도 있었지만 그런 시나리오에 대한 더 나은 해결책이 있다고 생각합니다.

다음은 코드입니다.

String regex = "([A-Z][a-z]+)";
String replacement = "$1_";

"CamelCaseToSomethingElse".replaceAll(regex, replacement); 

/*
outputs: Camel_Case_To_Something_Else_
desired output: Camel_Case_To_Something_Else
*/

질문 : 원하는 출력을 얻을 수있는 깔끔한 방법을 찾고 계십니까?


질문CaseFormat구아바에서보기

귀하의 경우에는 다음과 같습니다.

CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "SomeInput");

소문자와 대문자를 두 그룹으로 묶으면 괜찮을 것입니다.

public  class Main
{
    public static void main(String args[])
    {
        String regex = "([a-z])([A-Z]+)";
        String replacement = "$1_$2";
        System.out.println("CamelCaseToSomethingElse"
                           .replaceAll(regex, replacement)
                           .toLowerCase());
    }
}

아래 코드 스 니펫을 사용할 수 있습니다.

String replaceAll = key.replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase();

단순히 행의 시작이 아닌 것으로 이전 문자와 일치하지 않는 이유는 무엇 $입니까?

String text = "CamelCaseToSomethingElse";
System.out.println(text.replaceAll("([^_A-Z])([A-Z])", "$1_$2"));

이 버전은 이미 낙타 케이스에 넣어 수행해도 안전합니다.


너비가 0 인 미리보기 어설 션을 추가합니다.

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

(?=X)기타 문서를 읽으십시오 .

개인적으로 나는 실제로 문자열을 분할 한 다음 다시 결합했습니다. 올바르게 수행하면 더 빠를 수 있으며 정규 표현식 마법보다 코드를 훨씬 쉽게 이해할 수 있습니다. 오해하지 마세요. 저는 정규 표현식을 좋아합니다. 그러나 이것은 정말 깔끔한 정규 표현식이 아니며이 변환 은 고전적인 정규 표현식 작업도 아닙니다. 결국 소문자도하고 싶습니까?

못생긴하지만 빠른 해킹 교체하는 것 (.)([A-Z]+)으로 $1_$2하고 이후 전체 문자열을 소문자 (당신이 직접 교체를 소문자 수 펄 스타일 extrended regexps '에를 할 수 없다면!). 그래도 저는 아래에서 위로 전환 한 다음 변형 한 다음 결합하는 것이 적절하고 가장 읽기 쉬운 방법으로 분할하는 것을 고려합니다.


RegEx를 제공 할 수 없습니다. 어쨌든 엄청나게 복잡 할 것입니다.

약어를 자동으로 인식하여이 기능을 사용해보십시오.

불행히도 Guava lib는 대문자 약어를 자동으로 감지하지 않으므로 "bigCAT"는 "BIG_C_A_T"로 변환됩니다.

/**
 * Convert to UPPER_UNDERSCORE format detecting upper case acronyms
 */
private String upperUnderscoreWithAcronyms(String name) {
    StringBuffer result = new StringBuffer();
    boolean begin = true;
    boolean lastUppercase = false;
    for( int i=0; i < name.length(); i++ ) {
        char ch = name.charAt(i);
        if( Character.isUpperCase(ch) ) {
            // is start?
            if( begin ) {
                result.append(ch);
            } else {
                if( lastUppercase ) {
                    // test if end of acronym
                    if( i+1<name.length() ) {
                        char next = name.charAt(i+1);
                        if( Character.isUpperCase(next) ) {
                            // acronym continues
                            result.append(ch);
                        } else {
                            // end of acronym
                            result.append('_').append(ch);
                        }
                    } else {
                        // acronym continues
                        result.append(ch);
                    }
                } else {
                    // last was lowercase, insert _
                    result.append('_').append(ch);
                }
            }
            lastUppercase=true;
        } else {
            result.append(Character.toUpperCase(ch));
            lastUppercase=false;
        }
        begin=false;
    }
    return result.toString();
}

public class ReplaceFromCameltoSnake {
    public static void main(String args[]){
        String s1=" totalAmountWithoutDiscount";  
        String replaceString=s1.replaceAll("([A-Z]+)","\\_$1").toLowerCase(); 
        System.out.println(replaceString);  
    }
}

([A-Z][a-z\d]+)(?=([A-Z][a-z\d]+))

대문자 다음에 소문자를 검색해야합니다. 긍정적 인 미리보기는 대문자로 시작하고 소문자가 뒤 따르는 다른 단어를 찾지 만 일치에는 포함하지 않습니다.

Look here: http://regexr.com?30ooo


I've had to implement this to convert some keys in camel case format to lower case with underscores. The regular expression I came up with is:

(?<!^|_|[A-Z])([A-Z])

In english it stands for capital letter which is not preceded by the start of the string, an underscore or another capital letter.

In the samples below, the character in bold are the ones that should produce a match using the aforementioned regular expression:

  • CamelCaseToSomethingElse
  • camelCaseToSomethingElse
  • camel_case_to_something_else
  • Camel_Case_To_Something_Else
  • CAMEL_CASE_TO_SOMETHING_ELSE

Notice the expression does not affect string that are already in lower case + underscore format.

The replacement pattern would be:

_l$1

Which means lower case of first capturing group, first capturing group being the capital letter. You could lower case the whole string afterwards as well to normalize the last two samples from the list above.


Not sure it's possible to have something really solide with pure regex. Especially to support acronyms.

I have made a small function, inspired by @radzimir answer, that supports acronyms and no alphabetic character:

From https://gist.github.com/ebuildy/cf46a09b1ac43eea17c7621b7617ebcd:

private static String snakeCaseFormat(String name) {
    final StringBuilder result = new StringBuilder();

    boolean lastUppercase = false;

    for (int i = 0; i < name.length(); i++) {
        char ch = name.charAt(i);
        char lastEntry = i == 0 ? 'X' : result.charAt(result.length() - 1);
        if (ch == ' ' || ch == '_' || ch == '-' || ch == '.') {
            lastUppercase = false;

            if (lastEntry == '_') {
                continue;
            } else {
                ch = '_';
            }
        } else if (Character.isUpperCase(ch)) {
            ch = Character.toLowerCase(ch);
            // is start?
            if (i > 0) {
                if (lastUppercase) {
                    // test if end of acronym
                    if (i + 1 < name.length()) {
                        char next = name.charAt(i + 1);
                        if (!Character.isUpperCase(next) && Character.isAlphabetic(next)) {
                            // end of acronym
                            if (lastEntry != '_') {
                                result.append('_');
                            }
                        }
                    }
                } else {
                    // last was lowercase, insert _
                    if (lastEntry != '_') {
                        result.append('_');
                    }
                }
            }
            lastUppercase = true;
        } else {
            lastUppercase = false;
        }

        result.append(ch);
    }
    return result.toString();
}

참고URL : https://stackoverflow.com/questions/10310321/regex-for-converting-camelcase-to-camel-case-in-java

반응형