Login

Regular Expression Dictionary

Author:
skitch
Posted:
July 11, 2007
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

Cute little dictionary-like object that stores keys as regexs and looks up items using regex matches. It actually came in handy for a project where keys were regexes on URLs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import re

class RegExDict(object):
    """A dictionary-like object for use with regular expression keys.
    Setting a key will map all strings matching a certain regex to the
    set value.
    
    One caveat: the order of the iteration over items is unspecified,
    thus if a lookup matches multiple keys, it is unspecified which
    value will be returned - still, one such value will be returned.
    
    >>> d = RegExDict()
    >>> d[r'moo.*haha'] = 7
    >>> d[r'holler.*fool'] = 2
    >>> d['mooWORDhaha']
    7
    """
    def __init__(self):
        self._regexes = {}
        
    def __getitem__(self, name):
        for regex, value in self._regexes.items():
            m = regex.match(name)
            if m is not None:
                return value
        raise KeyError('Key does not match any regex')
    
    def __setitem__(self, regex, value):
        self._regexes[re.compile(regex)] = value

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.