按位置拆分字符串

2024-10-01 11:20:44 发布

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

我们知道anchorsword boundaries和{}在某个位置匹配,而不是匹配字符。
是否可以使用regex(特别是python)通过前面的一种方法拆分字符串?在

例如,考虑以下字符串:

"ThisisAtestForchEck,Match IngwithPosition." 

因此,我需要以下结果(以大写字母开头但不以空格开头的子字符串):

^{pr2}$

如果我分组,我得到:

>>> re.split(r'([A-Z])',s)
['', 'T', 'hisis', 'A', 'test', 'F', 'orch', 'E', 'ck,', 'M', 'atchingwith', 'P', 'osition.']

这是环顾四周的结果:

>>> re.split(r'(?<=[A-Z])',s)
['ThisisAtestForchEck,MatchingwithPosition.']
>>> re.split(r'((?<=[A-Z]))',s)
['ThisisAtestForchEck,MatchingwithPosition.']
>>> re.split(r'((?<=[A-Z])?)',s)
['ThisisAtestForchEck,MatchingwithPosition.']

请注意,如果要按以大写字母开头且前面有空格的子字符串拆分,例如:

['Thisis', 'Atest', 'Forch' ,'Eck,' ,'Match ', Ingwith' ,'Position.']

我可以使用re.findall,即:

>>> re.findall(r'([A-Z][^A-Z]*)',s)
['Thisis', 'Atest', 'Forch', 'Eck,', 'Match ', 'Ingwith', 'Position.']

但是第一个例子呢:有没有可能用re.findall来解决它?在


Tags: 字符串rematchposition大写字母split空格findall
3条回答

使用re.findall的方法:

re.findall(r'(?:[A-Z]|^[^A-Z\s])[^A-Z\s]*(?:\s+[A-Z][^A-Z]*)*',s)

当您决定将方法从split更改为findall时,第一项工作就是重新制定您的要求:“我要在每个大写字母上拆分字符串,而不是前面加空格”=>;“我要找到一个或多个子字符串,这些子字符串由空格分隔,以大写字母开头,但字符串的开头除外(如果字符串不是以大写字母开头)“

 (?<!\s)(?=[A-Z])

您可以使用此选项与regex模块一起拆分,因为re不支持0宽度拆分断言。在

^{pr2}$

或者

print [i for i in regex.split(r"(?<![\s])(?=[A-Z])",x,flags=regex.VERSION1) if i]

参见演示。在

https://regex101.com/r/sJ9gM7/65

我知道这可能不太方便,因为结果的元组性质。但我认为这个findall找到了您需要的:

re.findall(r'((?<!\s)[A-Z]([^A-Z]|(?<=\s)[A-Z])*)', s)
## returns [('Thisis', 's'), ('Atest', 't'), ('Forch', 'h'), ('Eck,', ','), ('Match Ingwith', 'h'), ('Position.', '.')]

这可用于以下列表理解,以给出所需的输出:

^{pr2}$

下面是一个使用split的黑客:

re.split(r'((?<!\s)[A-Z]([^A-Z]|(?<=\s)[A-Z])*)', s)[1::3]
## returns ['Thisis', 'Atest', 'Forch', 'Eck,', 'Match Ingwith', 'Position.']

相关问题 更多 >