构造正则表达式模式以仅识别python中的单独单词

时间:2018-01-15 03:33:03

标签: python regex

我有e_learning这个词,我希望在e_learning

中查看包含mylist的字词。
mylist = ['e_learning_environment', 'machine_learning', 'student_e_learning_platform']

我应该只输出e_learning_environmentstudent_e_learning_platform

我目前的代码如下。

for item in mylist:
   if 'e_learning' in 'machine_learning':
     print('yes')

然而,当我在python中使用in时,我也得到machine_learning。我可以使用正则表达式来避免它吗?请帮帮我!

1 个答案:

答案 0 :(得分:1)

您可以re使用lookbehind

import re
myrootword = 'e_learning' #target search variable
mylist = ['e_learning_environment', 'machine_learning', 'student_e_learning_platform']
new_list = [i for i in mylist if re.findall('(?<=^){}|(?<=\s){}|(?<=_){}'.format(*([myrootword]*3)), i)]

输出:

['e_learning_environment', 'student_e_learning_platform']