Python拆分字符串,但保留连续的大写字母

2024-05-16 02:47:30 发布

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

我想将字符串拆分为大写字母分隔的单词,但如果它包含连续的大写字母,则将其拆分为一个单词,直到最后一个字母(这可能会开始一个新词…)

例如:

splitThreeWords -> [split, three, words]
SplitThreeWords -> [split, three, words]
ILOSummit -> [ILO, summit]

Tags: 字符串字母大写字母单词splitthreewords新词
1条回答
网友
1楼 · 发布于 2024-05-16 02:47:30

re.split与捕获组一起使用(以保持拆分器模式),并过滤掉空块:

import re


def split_by_title_word(s):
    return [chunk for chunk in re.split(r"([A-Z][a-z]+)", s) if chunk]


print(split_by_title_word("splitThreeWords"))
print(split_by_title_word("SplitThreeWords"))
print(split_by_title_word("IOLSummit"))

输出

['split', 'Three', 'Words']
['Split', 'Three', 'Words']
['IOL', 'Summit']

模式[A-Z][a-z]+表示一个title

相关问题 更多 >