【发布时间】:2015-04-07 16:29:32
【问题描述】:
我们知道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 解决吗?
【问题讨论】:
-
您不能使用
split来执行此操作,因为它使用正则表达式来定义分隔符,这些分隔符被认为与被拆分的元素分开。在上一个示例中使用re.findall有什么问题? -
@Barmar 是的,我知道,但正如我所说的那样,我可以将第一个示例与
re.finall分开吗?我认为split对于此类任务更灵活!