python findall正则表达式

时间:2018-06-11 16:16:21

标签: python regex python-3.x

我有一个很长的字符串,我需要找到包含字符的单词' d'然后是角色'。

l=[" xkn59438","yhdck2","eihd39d9","chdsye847","hedle3455","xjhd53e","45da","de37dp"]
b=' '.join(l)
runs1=re.findall(r"\b\w?d.*e\w?\b",b)
print(runs1)

\ b是单词的边界,后跟任何字符(\ w?)等。 我得到一个空列表。

3 个答案:

答案 0 :(得分:1)

您可以通过对每个字符串单独应用基于正则表达式的搜索来大规模简化您的解决方案。

>>> [x for x in l if p.search(x)]

或者,

['chdsye847', 'hedle3455', 'xjhd53e', 'de37dp']

re.findall

为什么没有>>> re.findall(r"\b\S*d\S*e\S*", ' '.join(l)) ['chdsye847', 'hedle3455', 'xjhd53e', 'de37dp'] 工作?你正在搜索一个大字符串,中间的贪婪匹配正在搜索字符串。修复将会

\S

使用$("[src='myPic.jpg']") 匹配任何不是空格的内容。

答案 1 :(得分:0)

这样的事可能

\b\w*d\w*e\w*

请注意,您可以在此删除单词边界,因为
第一个\w保证之前的单词边界。

相同的\w*d\w*e\w*

答案 2 :(得分:0)

您可以过滤结果:

import re
l=[" xkn59438","yhdck2","eihd39d9","chdsye847","hedle3455","xjhd53e","45da","de37dp"]

pattern = r'd.*?e'

print(list(filter(lambda x:re.search(pattern,x),l)))

输出:

['chdsye847', 'hedle3455', 'xjhd53e', 'de37dp']