在非连续大写字母上拆分字符串

2024-09-29 21:25:55 发布

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

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

所以现在我要做的是:

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

但我想要的结果是:

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

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

谢谢


Tags: 字符串testrestringmy大写字母解决方案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)))

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

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

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']

相关问题 更多 >

    热门问题