我想要实现的目标是这样的:
>>> camel_case_split("CamelCaseXYZ")
['Camel', 'Case', 'XYZ']
>>> camel_case_split("XYZCamelCase")
['XYZ', 'Camel', 'Case']
所以我搜索并找到了这个完美的正则表达式:
(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])
作为我尝试的下一个逻辑步骤:
>>> re.split("(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "CamelCaseXYZ")
['CamelCaseXYZ']
为什么这不起作用,以及如何从 python 中的链接问题获得结果?
编辑:解决方案摘要
我用一些测试用例测试了所有提供的解决方案:
string: ''
AplusKminus: ['']
casimir_et_hippolyte: []
two_hundred_success: []
kalefranz: string index out of range # with modification: either [] or ['']
string: ' '
AplusKminus: [' ']
casimir_et_hippolyte: []
two_hundred_success: [' ']
kalefranz: [' ']
string: 'lower'
all algorithms: ['lower']
string: 'UPPER'
all algorithms: ['UPPER']
string: 'Initial'
all algorithms: ['Initial']
string: 'dromedaryCase'
AplusKminus: ['dromedary', 'Case']
casimir_et_hippolyte: ['dromedary', 'Case']
two_hundred_success: ['dromedary', 'Case']
kalefranz: ['Dromedary', 'Case'] # with modification: ['dromedary', 'Case']
string: 'CamelCase'
all algorithms: ['Camel', 'Case']
string: 'ABCWordDEF'
AplusKminus: ['ABC', 'Word', 'DEF']
casimir_et_hippolyte: ['ABC', 'Word', 'DEF']
two_hundred_success: ['ABC', 'Word', 'DEF']
kalefranz: ['ABCWord', 'DEF']
总之,您可以说 @kalefranz 的解决方案与问题不匹配(参见最后一个案例),而 @casimir et hippolyte 的解决方案占用了一个空格,从而违反了拆分不应更改各个部分的想法。其余两个替代方案之间的唯一区别是,我的解决方案返回一个列表,其中空字符串输入上包含空字符串,而 @200_success 的解决方案返回一个空列表。
我不知道 python 社区在这个问题上的立场如何,所以我说:我对其中任何一个都很好。由于 200_success 的解决方案更简单,我接受它作为正确答案。