1

I need to find a the whole word within a string which contains a sub string.

For instance If replacement is a string and I will search for replace , so it will match replacement and it should return replacement.

Here is what I tried

>>> a = 'replacement replace  filereplace   filereplacer'
>>> re.findall(r'replace',a)

['replace', 'replace', 'replace', 'replace']

But what I need is:

['replacement', 'replace', 'filereplace', 'filereplacer']
Karthikeyan KR
  • 1,134
  • 1
  • 17
  • 38

2 Answers2

3

Match with word boundaries and \w (which is also robust to punctuation):

import re

a = 'replacement replace  filereplace,   filereplacer.  notmatched'
print(re.findall(r'\b\w*replace\w*\b',a))

result:

['replacement', 'replace', 'filereplace', 'filereplacer']
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

Split your list using your separator (space here):

l_s = a.split()

Then look for your substring in each element of the list:

[word for word in l_s if string_to_find in word]
Jean Rostan
  • 1,056
  • 1
  • 8
  • 16