import re
reg = re.compile(r'\b(apple)(?:\W+\w+){0,4}?\W+(tree|plant|garden)')
reg.findall('my\napple tree in the garden')
reg.findall('apple\ntree in the garden')
import re
reg = re.compile(r'\b(apple)(?:[^\n\w]+\w+){0,4}?[^\n\w]+(tree|plant|garden)')
print(reg.findall('my\napple tree in the garden'))
# [('apple', 'tree')]
print(reg.findall('apple\ntree in the garden'))
# []
1条答案
按热度按时间gkn4icbw1#
您的
\W
匹配换行符。要排除它们,请将\W
替换为[^\w\n]
: