【发布时间】:2014-04-22 20:36:19
【问题描述】:
给定一个列表
list=['beak','back','bear','kill','keel']
例如,我想使用通配符执行搜索以返回与模式 k**l 匹配的所有单词。我可以通过以下方式轻松做到这一点:
regex=re.compile('k..l')
matches=[string for string in list if re.match(regex, string)]
但是,我还想访问匹配位置的索引并拥有类似的东西:
matches=kill, keel
locs=3,4
我想要索引的原因是,一旦找到匹配项,我想访问 df 中的一整行(包含其他变量)。
感谢您的帮助。
【问题讨论】:
-
如果你对匹配元组和索引没问题,你可以使用
[(idx, string) for idx, string in enumerate(list) if re.match(regex, string)]。然后你可以使用zip来分隔数据。
标签: python regex string wildcard