Question

I need to parse DHCP log data which is like below:

2013-11-15 09:42:02 localhost dhcpd: DHCPACK on 10.51.1.242 to 00:1e:8c:21:83:a0 (Hostname Unsuitable for Printing) via eth2

I wrote a regex pattern to gather all matched values and it like this:

(?P<date>[\d{2,4}-]*[\d{2}:\s]*)\s(?P<host>\S+)\s*(?P<facility>\s*\S*:)\s*((?P<action>DHCP*\S*)\s*|(?P<mac>([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]){2})\s*|(?P<message>\S*)\s*|(\s*))*

After re.search(regex, text).groupdict() command it gives me this dict:

{u'facility': u'dhcpd:', u'host': u'localhost', u'date': u'2013-11-15 09:42:02', u'mac': u'00:1e:8c:21:83:a0', u'action': u'DHCPACK', u'message': u''}

As it is seen that every single item returns me correct match but message part which placed in parentheses and I tried with too many variations to get it. (?P<message>\((.*)\)) pattern works fine and returns {u'message': u'(Hostname Unsuitable for Printing)'} if I use it as single otherwise It does not match at all.

I stuck with this and really need help.

No correct solution

OTHER TIPS

I'm not sure why you're using so many | operands. I stripped them out and used \s+ as delimiters and $ to match the end of string as a delimiter for the message but this works for me:

import re
text = r'2013-11-15 09:42:02 localhost dhcpd: DHCPACK on 10.51.1.242 to 00:1e:8c:21:83:a0 (Hostname Unsuitable for Printing) via eth2'
my_regexp = r'^(?P<date>[\d{2,4}-]*[\d{2}:\s]*)\s+(?P<host>\S+)\s+(?P<facility>\s*\S*):(\s+(?P<action>DHCP*\S*).+(?P<mac>([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]){2})\s+(?P<message>.*))*$'
print re.search( my_regexp, text).groupdict()

Output:

{'facility': 'dhcpd', 'host': 'localhost', 'date': '2013-11-15 09:42:02', 'mac': '00:1e:8c:21:83:a0', 'action': 'DHCPACK', 'message': '(Hostname Unsuitable for Printing) via eth2'}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top