2024-09-29 21:25:55 发布
网友
我试图用大写字母拆分字符串,但我不想拆分两个连续的大写字母
所以现在我要做的是:
my_string == "TTestStringAA" re.findall('[a-zA-Z][^A-Z]*', my_string) >>> ['T', 'Test', 'String', 'A', 'A']
但我想要的结果是:
>>> ['TTest', 'String', 'AA']
这个问题有一个干净简单的解决方案吗
谢谢
下面的正则表达式将返回正确的结果
[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]*符合您的要求:
[A-Z]+[a-z]*
>>> re.findall(r'[A-Z]+[a-z]*', my_string) ['TTest', 'String', 'AA']
将re.split与
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']
下面的正则表达式将返回正确的结果
测试用例:
我相信
[A-Z]+[a-z]*
符合您的要求:将
re.split
与见proof
解释
Python code:
结果:
相关问题 更多 >
编程相关推荐