Python:将camel case转换为使用RegEx分隔的空格,并将首字母缩略词转换为acoun

2024-04-29 00:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python将camel case转换为空格分隔的值。例如:

divLineColor -> div Line Color

这一行成功地做到了:

label = re.sub("([A-Z])"," \g<0>",label)

我遇到的问题是像simpleBigURL这样的事情,他们应该这样做:

simpleBigURL -> simple Big URL

我不完全确定如何得到这个结果。救命啊!


我试过一件事:

label = re.sub("([a-z])([A-Z])","\g<0> \g<1>",label)

但这会产生奇怪的结果,比如:

divLineColor -> divL vineC eolor

我还认为使用(?!...)可以工作,但我没有任何运气。


Tags: divreurllinesimple事情labelcolor
3条回答

\g<0>引用整个模式的匹配字符串,而\g<1>引用第一个子模式的匹配字符串((…))。所以您应该使用\g<1>\g<2>代替:

label = re.sub("([a-z])([A-Z])","\g<1> \g<2>",label)

这应该适用于“divLineColor”、“simpleBigURL”、“OldHTMLFile”和“SQLServer”。

label = re.sub(r'((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))', r' \1', label)

说明:

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)

如果找到匹配项,则将其替换为' \1',该字符串由前导空格和匹配项本身组成。

匹配的替代项1是一个大写字符,但前提是它前面有一个小写字符。我们想把abYZ翻译成ab YZ,而不是ab Y Z

匹配的替代项2是一个大写字符,但前提是它后面跟一个小写字符,而不是字符串的开头。我们想把ABCyz翻译成AB Cyz,而不是A B Cyz

我知道,这不是regex。但是,您也可以像这样使用^{}

>>> s = 'camelCaseTest'
>>> ''.join(map(lambda x: x if x.islower() else " "+x, s))
'camel Case Test'

相关问题 更多 >