我试图使用python将camel case转换为空格分隔值.例如:
divLineColor - > div Line Color
这条线成功地做到了:
label = re.sub("([A-Z])"," \g<0>",label)
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是simpleBigURL
他们应该这样做:
simpleBigURL - >简单的大URL
我不完全确定如何得到这个结果.救命!
这是我尝试过的一件事:
label = re.sub("([a-z])([A-Z])","\g<0> \g<1>",label)
Run Code Online (Sandbox Code Playgroud)
但这会产生奇怪的结果,如:
divLineColor - > divL vineC eolor
我也在想使用它(?!...)
可以工作,但我没有运气.
Mat*_*ias 27
这应该与'divLineColor','simpleBigURL','OldHTMLFile'和'SQLServer'一起使用.
label = re.sub(r'((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))', r' \1', label)
Run Code Online (Sandbox Code Playgroud)
说明:
label = re.sub(r"""
( # start the group
# alternative 1
(?<=[a-z]) # current position is preceded by a lower char
# (positive lookbehind: does not consume any char)
[A-Z] # an upper char
#
| # or
# alternative 2
(?<!\A) # current position is not at the beginning of the string
# (negative lookbehind: does not consume any char)
[A-Z] # an upper char
(?=[a-z]) # matches if next char is a lower char
# lookahead assertion: does not consume any char
) # end the group""",
r' \1', label, flags=re.VERBOSE)
Run Code Online (Sandbox Code Playgroud)
如果找到匹配,则将其替换为' \1'
,该字符串由前导空白和匹配本身组成.
匹配的替代1是上部字符,但前提是前面是较低的字符.我们要翻译abYZ
来ab YZ
,而不是ab Y Z
.
匹配的替代2是上部字符,但仅当它后跟较低的字符而不是字符串的开头时.我们要翻译ABCyz
来AB Cyz
,而不是A B Cyz
.
Gum*_*mbo 19
\g<0>
引用整个模式\g<1>
的匹配字符串,同时引用第一个子模式((…)
)的匹配字符串.所以你应该使用\g<1>
而\g<2>
不是:
label = re.sub("([a-z])([A-Z])","\g<1> \g<2>",label)
Run Code Online (Sandbox Code Playgroud)
我知道,这不是正则表达式.但是,你也可以map
这样使用
>>> s = 'camelCaseTest'
>>> ''.join(map(lambda x: x if x.islower() else " "+x, s))
'camel Case Test'
Run Code Online (Sandbox Code Playgroud)