Skip to content

Instantly share code, notes, and snippets.

@anfedorov
Created March 2, 2010 20:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anfedorov/319905 to your computer and use it in GitHub Desktop.
Save anfedorov/319905 to your computer and use it in GitHub Desktop.
import re
class ReDict(dict):
def __setitem__(self, key, value):
dict.__setitem__(self, re.compile(key), value)
def __getitem__(self, key):
return [v for k,v in self.items() if k.match(key)]
# Example:
rd = ReDict()
rd['^foo$'] = 1
rd['^bar*$'] = 2
rd['^bar$'] = 3
assert rd['foo'] == [1]
assert rd['barrrr'] == [2]
assert rd['bar'] == [2,3]
@me-suzy
Copy link

me-suzy commented Jun 3, 2021

nice one. It will be a great Idea to make a Batch Processor for regex Find and Replace. Suppose I have 6 or 10 regex formula for search and replace. For example First 2 regex:

Search: <title>.*\|\K(.*)(</title>)
Replace by: \x20 Test \x20\2

Search: <em>.*\|.*</em>)(</title>)
Replace by: \x20\2

and so one,. The Python code should be run these regex, in the order I choose, and to be able to add always a new regex.

It will be a great idea. But for regex, you have to consider also the option .matches newsline

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment