如何将正则表达式提供给需要字符串的方法?

How to feed a regular expression to a method that requires a string?

我想要实现的是基于上一个问题的投票答案:Check if node exists in h5py

基本上我要替换:

"/some/path" in h5File

类似的东西:

import re
re.compile(r'/some/[pattern]+') in h5File

in 关键字不能采用正则表达式,但您可以使用列表理解或内置的 filter 从字典中获取与给定正则表达式匹配的所有键。

例如

found_keys = [k for k in h5file if re.match(r'/some/[pattern]+', k)]

regex = re.compile(r'/some/[pattern]+')
found_keys = filter(regex.match, h5file)