Python: convert camel case to space delimited using RegEx and taking Acronyms into account

后端 未结 10 1903
逝去的感伤
逝去的感伤 2020-12-29 04:38

I am trying to convert camel case to space separated values using python. For example:

divLineColor -> div Line Color

This lin

相关标签:
10条回答
  • 2020-12-29 05:15

    Here's my simple solution, which works with PCRE-like implementations, including Python:

    /(?<=[a-zA-Z])(?=[A-Z])/g
    

    Then, simply replace all matches with a single space (). Putting it all together:

    re.sub(r'(?<=[a-zA-Z])(?=[A-Z])', ' ', yourCamelCaseString);
    

    SSCCE

    0 讨论(0)
  • 2020-12-29 05:15

    Hope this method helps :

    public static String convertCamelCaseToStatement(String camelCase) {
        StringBuilder builder = new StringBuilder();
        for (Character c : camelCase.toCharArray()) {
            if (Character.isUpperCase(c)) {
                builder.append(" ").append(c);
            } else {
                builder.append(c);
            }
        }
        return builder.toString();
    }
    
    0 讨论(0)
  • 2020-12-29 05:17

    \g<0> references the matched string of the whole pattern while \g<1> refereces the matched string of the first subpattern ((…)). So you should use \g<1> and \g<2> instead:

    label = re.sub("([a-z])([A-Z])","\g<1> \g<2>",label)
    
    0 讨论(0)
  • 2020-12-29 05:17

    (?<=[a-z])([A-Z])
    or
    ([a-z])([A-Z])

    0 讨论(0)
提交回复
热议问题