0

I want to match all dhcp leases that have given mac address.

I wrote this code

fh = open(leaseFile)
lines = fh.read()
fh.close()
regex = r"lease\s*[0-9\.]+\s*\{[^\{\}]*%s[^\{\}]*?\}" % mac #mac comes as parameter
m = re.findall(regex,lines,re.DOTALL)

This worked well if a lease don't contain '}' character. But if it does, my regex failed. For example:

lease 10.14.53.253 {
  starts 3 2012/10/17 09:27:20;
  ends 4 2012/10/18 09:27:20;
  tstp 4 2012/10/18 09:27:20;
  binding state free;
  hardware ethernet 00:23:18:62:31:5b;
  uid "\001\000\013OW}k";
}

I couldn't figure out how I handle this exception. Thanks for any advice...

EDIT

After research, I decided to use this regex with MULTILINE mode. It worked for all leases that I tried.

fh = open(leaseFile)
lines = fh.read()
fh.close()
regex = r"lease\s*[0-9\.]+\s*\{[^\{\}]*%s[\s\S]*?^\}" % mac #mac comes as parameter
m = re.findall(regex,lines,re.MULTILINE)
ibrahim
  • 3,254
  • 7
  • 42
  • 56
  • See [Removing a lease that has giving mac from dhcpd.leases with python?](http://stackoverflow.com/questions/13623593/13624313#13624313). Do not use regular expressions for this task, it's not a regular expression problem. – Martijn Pieters Dec 03 '12 at 12:41
  • I know it. this question was also mine. But I couldn't use pyparsing. – ibrahim Dec 03 '12 at 12:43
  • I know it was your question. The problem is that DHCP leases are, like [HTML and XML](http://stackoverflow.com/a/1732454/100297), a difficult task to parse for regular expressions. You should not use regular expressions for this task. Use line-by-line reading if you have to, but a regexp is not going to solve this for you. Using a dedicated parser or pyparsing instead would be *much easier*. – Martijn Pieters Dec 03 '12 at 12:44

1 Answers1

2
regex = r'(lease\s*[0-9\.]+\s*\{[^\{\}]*%s[^\{\}]*(.*"[^\{\}]*\}|\}))' % mac #mac comes as parameter
m = re.findall(regex,lines)

This should do the trick.

Alptugay
  • 1,676
  • 4
  • 22
  • 29