我们知道anchors
、word 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
来解决它?在
使用
re.findall
的方法:当您决定将方法从
split
更改为findall
时,第一项工作就是重新制定您的要求:“我要在每个大写字母上拆分字符串,而不是前面加空格”=>;“我要找到一个或多个子字符串,这些子字符串由空格分隔,以大写字母开头,但字符串的开头除外(如果字符串不是以大写字母开头)“您可以使用此选项与regex模块一起拆分,因为re不支持0宽度拆分断言。在
^{pr2}$或者
参见演示。在
https://regex101.com/r/sJ9gM7/65
我知道这可能不太方便,因为结果的元组性质。但我认为这个
findall
找到了您需要的:这可用于以下列表理解,以给出所需的输出:
^{pr2}$下面是一个使用
split
的黑客:相关问题 更多 >
编程相关推荐