aluckdog
我不知道为什么这些都如此复杂。对于大多数情况,简单的表达式([A-Z]+)将起到作用>>> re.sub('([A-Z]+)', r'_\1','CamelCase').lower()'_camel_case' >>> re.sub('([A-Z]+)', r'_\1','camelCase').lower()'camel_case'>>> re.sub('([A-Z]+)', r'_\1','camel2Case2').lower()'camel2_case2'>>> re.sub('([A-Z]+)', r'_\1','camelCamelCase').lower()'camel_camel_case'>>> re.sub('([A-Z]+)', r'_\1','getHTTPResponseCode').lower()'get_httpresponse_code'要忽略第一个字符,只需在后面添加外观 (?!^)>>> re.sub('(?!^)([A-Z]+)', r'_\1','CamelCase').lower()'camel_case'>>> re.sub('(?!^)([A-Z]+)', r'_\1','CamelCamelCase').lower()'camel_camel_case'>>> re.sub('(?!^)([A-Z]+)', r'_\1','Camel2Camel2Case').lower()'camel2_camel2_case'>>> re.sub('(?!^)([A-Z]+)', r'_\1','getHTTPResponseCode').lower()'get_httpresponse_code'如果你想将ALLCaps分离到all_caps并期望你的字符串中的数字,你仍然不需要做两个单独的运行只需使用|这个表达式((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))几乎可以处理书中的每个场景>>> a = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')>>> a.sub(r'_\1', 'getHTTPResponseCode').lower()'get_http_response_code'>>> a.sub(r'_\1', 'get2HTTPResponseCode').lower()'get2_http_response_code'>>> a.sub(r'_\1', 'get2HTTPResponse123Code').lower()'get2_http_response123_code'>>> a.sub(r'_\1', 'HTTPResponseCode').lower()'http_response_code'>>> a.sub(r'_\1', 'HTTPResponseCodeXYZ').lower()'http_response_code_xyz'这一切都取决于你想要什么,所以使用最适合你需求的解决方案,因为它不应该过于复杂。的nJoy!