J Cena
J Cena

Reputation: 1053

Construct regex pattern to identify only seperate words in python

I have the term e_learning and I want to see what are terms that includes e_learning in mylist

mylist = ['e_learning_environment', 'machine_learning', 'student_e_learning_platform']

I should only get e_learning_environment and student_e_learning_platform as the output.

My current code is as follows.

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

However when I use in in python I also get machine_learning. Can I avoid it using regex? Please help me!

Upvotes: 0

Views: 44

Answers (1)

Ajax1234
Ajax1234

Reputation: 71451

You can use re with a 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)]

Output:

['e_learning_environment', 'student_e_learning_platform']

Upvotes: 1

Related Questions