Python:使用RegEx将camel case转换为空格并考虑缩略语

six*_*ude 20 python regex

我试图使用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是上部字符,但前提是前面是较低的字符.我们要翻译abYZab YZ,而不是ab Y Z.

匹配的替代2是上部字符,但仅当它后跟较低的字符而不是字符串的开头时.我们要翻译ABCyzAB Cyz,而不是A B Cyz.

  • 一年后回顾我的答案:"天哪,我应该添加一些评论".:) (3认同)
  • 这就像肉体中的刺.我现在补充说明了. (3认同)

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)

  • @NasBanov 这是一个更复杂的问题,可能需要人工智能进行拼写检查。例如,“MyJSONAISpec”应该是“My JSON AI Spec”,但是什么正则表达式可以解决这个问题?您可以获取“我的 JSONAISpec”、“我的 JSONAI 规范”或“我的 JSONAI 规范”。 (2认同)
  • @Supuhstar 不能指望这里有魔法精灵。我认为“My JSONAI Spec”是您示例的预期分割。应该更改大小写来标记单独的单词 - 大概您希望 JSON 和 AI 对于人类来说在视觉上是分开的,因此名称应该是“MyJsonAISpec”或“MyJSONAiSpec”或“MyJsonAiSpec”或使用下划线。我们不要让机器人理解人类不清楚的事情。Mathias 在下面发布了合理的解决方案 (2认同)

Ade*_*taş 9

我知道,这不是正则表达式.但是,你也可以map这样使用

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

  • -1。这个问题**非常具体**要求一些可以与“simpleBigURL”等一起使用的东西(即所有大写字母的首字母缩略词),这是您的解决方案完全失败的。 (2认同)