我们知道anchors
,word boundaries
和lookaround
在某个位置匹配,而不是匹配字符。
是否可以使用正则表达式(特别是在python中)通过上述方式之一拆分字符串?
例如,考虑以下字符串:
"ThisisAtestForchEck,Match IngwithPosition."
所以我想要以下结果(以大写字母开头但不以空格开头的子字符串):
['Thisis', 'Atest', 'Forch' ,'Eck,' ,'Match Ingwith' ,'Position.']
如果我分组分组,我得到:
>>> 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
解决呢?
python大神给出的解决方案
re.findall
的一种方式:
re.findall(r'(?:[A-Z]|^[^A-Z\s])[^A-Z\s]*(?:\s+[A-Z][^A-Z]*)*',s)
当您决定将方法从split
更改为findall
时,第一项工作就是重新定义您的要求:“我想在每个大写字母上拆分字符串,且不带空格” =>“我想找到一个或多个由以大写字母开头的空格分隔的子字符串,但字符串的开头除外(如果字符串不是以大写字母开头的话)”