[英]Trying to find two words before and after a group of words with regex
sentence = "I love the grand mother bag i bought . I love my sister's ring "
import re
regex = re.search('(\w+){2}the grand mother bag(\w+){2}', sentence)
print(regex.groups())
I should have extracted: I love and I bought.我应该提取:我爱,我买了。
Any idea where I went wrong?知道我哪里出错了吗?
Change your regex: \w does not match word but a character so you extract only 2 characters:更改您的正则表达式:\w 不匹配单词而是字符,因此您只提取 2 个字符:
>>> re.search('(\w+\s+\w+)\s+the grand mother bag\s+(\w+\s+\w+)', sentence).groups()
('I love', 'i bought')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.