ActiveState Code

Recipe 442497: Pattern List


I found my self want to express -string- in -list of regular expressions- and so I wrote this quick object to do the trick for me. It takes a list of strings containing regular expressions, compiles them into an internal list and then using the __contains__ operation ("in") looks to see if a given string contains any of the expressions. The first success returns True otherwise it returns False.

Python
 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
import re

class PatternList( object ):
    """A Patternlist is a list of regular expressions. the 'in' operator
    allows a string to be compared against each expression (using search 
    NOT match)"""
    def __init__(self , patterns = []):
        self.patterns = []
        for p in patterns:
            self.add( p )        
    def add( self , pattern ):
        pat = re.compile( pattern )
        self.patterns.append( pat )
    def __contains__(self , item ):
        ret = False
        for p in self.patterns:
            if p.search( item ):
                ret= True
                break
        return ret       

if __name__=="__main__":
    examplelist = PatternList( [ ".*txt$"  ,  ".*doc$"  ])
    assert( "test.txt" in examplelist )
    assert( "test.xls" not in examplelist )

Discussion

The main object was to make my code read cleanly.

Sign in to comment