Debian Codegraph @

stetl/filters/regexfilter.py

raw
1 #!/usr/bin/env python
2 #
3 # Extracts data from a string using a regular expression and generates a record.
4 #
5 # Author: Frank Steggink
6 import re
7
8 from stetl.component import Config
9 from stetl.filter import Filter
10 from stetl.packet import FORMAT
11 from stetl.util import Util
12
13 log = Util.get_log("regexfilter")
14
15
16 class RegexFilter(Filter):
17 """
18 Extracts data from a string using a regular expression and returns the named groups as a record.
19 consumes=FORMAT.string, produces=FORMAT.record
20 """
21
22 # Start attribute config meta
23 # Applying Decorator pattern with the Config class to provide
24 # read-only config values from the configured properties.
25
26 @Config(ptype=str, default=None, required=True)
27 def pattern_string(self):
28 """
29 Regex pattern string. Should contain named groups.
30 """
31 pass
32
33 # End attribute config meta
34
35 # Constructor
36 def __init__(self, configdict, section, consumes=FORMAT.string, produces=FORMAT.record):
37 Filter.__init__(self, configdict, section, consumes, produces)
38
39 self.regex_object = re.compile(self.pattern_string, re.S)
40
41 def init(self):
42 log.info('Init: regex filter')
43 if self.pattern_string is None:
44 # If no pattern_string is present:
45 err_s = 'The pattern_string needs to be configured'
46 log.error(err_s)
47 raise ValueError('The pattern_string needs to be configured')
48
49 def exit(self):
50 log.info('Exit: regex filter')
51
52 def invoke(self, packet):
53 if packet.data is None:
54 return packet
55
56 m = self.regex_object.match(packet.data)
57 if m is not None:
58 packet.data = m.groupdict()
59 else:
60 packet.data = {}
61
62 return packet