Similar thing to regex groups in Lua?

Viewed 60

I have a log with lines like this:

Jun 21 06:25:07 172.25.1.1 kernel: DROP IN=ppp0 OUT= MAC= SRC=206.221.177.2 DST=185.79.95.179 LEN=40 TOS=0x00 PREC=0x00 TTL=239 ID=25584 PROTO=TCP SPT=40001 DPT=58571 SEQ=1145952392 ACK=0 WINDOW=1024 RES=0x00 SYN URGP=0

I'd like to extract some information from it: the date, the source IP etc. With a regexp I can do it (in python or perl): '^(... ..) .* DROP .* SRC=(\S+)' But how can I do this in Lua?

1 Answers

You may use a solution based on string.match:

local s = "Jun 21 06:25:07 172.25.1.1 kernel: DROP IN=ppp0 OUT= MAC= SRC=206.221.177.2 DST=185.79.95.179 LEN=40 TOS=0x00 PREC=0x00 TTL=239 ID=25584 PROTO=TCP SPT=40001 DPT=58571 SEQ=1145952392 ACK=0 WINDOW=1024 RES=0x00 SYN URGP=0 ]"
date,ip = string.match(s, "^(%w+ %d+ %d%d:%d%d:%d%d) .* DROP .* SRC=(%S+)")
print (date) -- Jun 21 06:25:07
print (ip)   -- 206.221.177.2

See the Lua demo online.

Pattern details

  • ^ - start of string
  • (%w+ %d+ %d%d:%d%d:%d%d) - Capturing group #1 (note its value will get assigned to date, the first var on the left hand side): 1+ alphanumerics, space, 1+ digits, space, 2 digits, :, 2 digits, : and 2 digits
  • .* DROP .* SRC= - literal string
  • (%S+) - Capturing group #2 (note its value will get assigned to ip, the second var on the left hand side): 1 or more non-whitespace chars.

Just remember that when there are capturing groups in a Lua pattern, the string.match function will return all of them. This is very handy.

Related