0

What I want to achieve is based on the voted answer for a previous question: Check if node exists in h5py

Basically I want to replace:

"/some/path" in h5File

with something like:

import re
re.compile(r'/some/[pattern]+') in h5File
Community
  • 1
  • 1
Hailiang Zhang
  • 17,604
  • 23
  • 71
  • 117
  • 1
    You can't, that doesn't make sense. Unless the `__contains__` method than implements `in` is written to accept a compiled regular expression, or you can get the actual string to match against, there's no way to do this. – jonrsharpe Nov 12 '15 at 16:56

1 Answers1

2

The in keyword can't take a regex, but you could use list-comprehension or filter built-in to get all keys from a dictionary that match a given regex.

E.g.

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

or

regex = re.compile(r'/some/[pattern]+')
found_keys = filter(regex.match, h5file)
memoselyk
  • 3,993
  • 1
  • 17
  • 28
  • 1
    Also, if Hailiang only wants to check whether there is a matching key, it is possible to merely call `any(regex.match(k) for k in h5file)`. – brandizzi Nov 12 '15 at 17:09