Python使用substring在字符串中查找字符串

时间:2018-04-19 13:10:21

标签: python regex string

我需要在包含子字符串的字符串中找到整个单词。

例如,如果替换是一个字符串,我将搜索替换,所以它将匹配替换,它应该返回替换。

这是我试过的

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

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

但我需要的是:

['replacement', 'replace', 'filereplace', 'filereplacer']

2 个答案:

答案 0 :(得分:3)

与单词边界和\w匹配(对标点符号也很健壮):

import re

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

结果:

['replacement', 'replace', 'filereplace', 'filereplacer']

答案 1 :(得分:1)

使用分隔符(此处为空格)拆分列表:

l_s = a.split()

然后在列表的每个元素中查找您的子字符串:

[word for word in l_s if string_to_find in word]
相关问题