我试图创建一个正则表达式,将字符串作为字符串并将其分为三组:(1)字符串开头的特定单词列表中的任何一个。(2)字符串末尾的任何特定单词列表。(3)这两个匹配项之间的所有字母/空格。
例如,我将使用以下两个字符串:
'There was a cat in the house yesterday'
'Did you see a cat in the house today'
我希望将字符串分成多个捕获组,以便match对象m.groups()
将分别为每个字符串返回以下内容:
('There', ' was a cat in the house ', 'yesterday')
('Did', ' you see a cat in the house ', 'today')
最初,我想出了以下正则表达式:
r = re.compile('^(There|Did) ( |[A-Za-z])+ (today|yesterday)$')
但是,这返回:
('There', 'e', 'yesterday')
('Did', 'e', 'today')
所以这只是给我最后一组匹配的字符。我了解到这是行不通的,因为捕获组将仅返回匹配的最后一次迭代。因此,我在中间捕获组周围加上了括号,如下所示:
r = re.compile('^(There|Did) (( |[A-Za-z])+) (today|yesterday)$')
但是现在,尽管它至少捕获了中间组,但它还在中返回了一个额外的“ e”字符m.groups()
,即:
('There', 'was a cat in the house', 'e', 'yesterday')
...尽管我觉得这与回溯有关,但我不知道为什么会发生。有人可以向我解释为什么我得到这个结果,以及如何得到期望的结果吗?
r = re.compile('^(There|Did) (( |[A-Za-z])+) (today|yesterday)$')
^ ^ ^
你有一些不必要的东西。删除这些内容并在中间组中添加空格:
r = re.compile('^(There|Did) ([A-Za-z ]+) (today|yesterday)$')
^ space
例子:
>>> r = re.compile('^(There|Did) ([A-Za-z ]+) (today|yesterday)$')
>>> r.search('There was a a cat in the hosue yesterday').groups()
('There', 'was a a cat in the hosue', 'yesterday')
另外,如果您希望这些空间成为中间(第二个)组的一部分,请取出两个捕获组之间的空间
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句