【问题标题】:Split string on non consecutive capital letters在非连续大写字母上拆分字符串
【发布时间】:2021-01-09 21:48:49
【问题描述】:

我试图用大写字母分割一个字符串,但我不想分割两个连续的大写字母。

所以现在我正在这样做:

my_string == "TTestStringAA"
re.findall('[a-zA-Z][^A-Z]*', my_string)
>>> ['T', 'Test', 'String', 'A', 'A']

但我正在寻找的输出是:

>>> ['TTest', 'String', 'AA']

这个问题有干净简单的解决方案吗?

谢谢!

【问题讨论】:

    标签: python regex string split capitalization


    【解决方案1】:

    我相信[A-Z]+[a-z]* 符合您的要求:

    >>> re.findall(r'[A-Z]+[a-z]*', my_string)
    ['TTest', 'String', 'AA']
    

    【讨论】:

    • 这对我有用,但我做了一些小改动,因为我发现这个解决方案在开始时没有保留小写字母并且数字没有正确拆分所以最后这就是我想出的解决方案: r'[A-Z0-9]*[az]*'
    【解决方案2】:

    re.split 用于

    (?<=[a-z])(?=[A-Z])
    

    proof

    说明

    --------------------------------------------------------------------------------
      (?<=                     look behind to see if there is:
    --------------------------------------------------------------------------------
        [a-z]                    any character of: 'a' to 'z'
    --------------------------------------------------------------------------------
      )                        end of look-behind
    --------------------------------------------------------------------------------
      (?=                      look ahead to see if there is:
    --------------------------------------------------------------------------------
        [A-Z]                    any character of: 'A' to 'Z'
    --------------------------------------------------------------------------------
      )                        end of look-ahead
    

    Python code:

    import re
    pattern = r"(?<=[a-z])(?=[A-Z])"
    test = "TTestStringAA"
    print(re.split(pattern, test))
    

    结果:

    ['TTest', 'String', 'AA']
    

    【讨论】:

      【解决方案3】:

      以下正则表达式将返回正确的结果。

      [a-z]*[A-Z]+[a-z]*|[a-z]+$
      

      测试用例:

      tests = ['a', 'A', 'aa', 'Aa' 'AaAaAAAaAa', 'aTTestStringAA']
      regex = re.compile(r'[a-z]*[A-Z]+[a-z]*|[a-z]+$')
      for test in tests:
          print('{} => {}'.format(test, re.findall(regex, test)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        • 2011-05-28
        相关资源
        最近更新 更多