Pattern matches string in Lua

I have the following line for splitting into a table using Lua: (the data is aligned with each other. I did not know how to write in the format like on this site)

IP: 192.168.128.12
MAC: AF: 3G: 9F: c9: 32: 2E
Expires: Fri Aug 13 20:04:53 2010
Time Left: 11040 seconds

The result should be placed in the table as follows:

t = {"IP": "192.168.128.12", "MAC": "AF: 3G: 9F: c9: 32: 2E", "Expires": "Fri Aug 13 20:04:53 2010", "Time Left ":" 11040 seconds "}

I tried:

for k,v in string.gmatch(data, "([%w]+):([%w%p%s]+\n") do t[k] = v end 

This was my best attempt.

+4
source share
3 answers

If I understood your use case, the following should do the trick. This may require a bit of customization though.

 local s = "IP: 192.168.128.12 MAC: AF:3G:9F:c9:32:2E Expires: Fri Aug 13 20:04:53 2010 Time Left: 11040 seconds" local result = {} result["IP"] = s:match("IP: (%d+.%d+.%d+.%d+)") result["MAC"] = s:match("MAC: (%w+:%w+:%w+:%w+:%w+:%w+)") result["Expires"] = s:match("Expires: (%w+ %w+ %d+ %d+:%d+:%d+ %d+)") result["Time Left"] = s:match("Time Left: (%d+ %w+)") 
+3
source

Assuming data aligned with each other means the following:

  IP: 192.168.128.12
 MAC: AF: 3G: 9F: c9: 32: 2E
 Expires: Fri Aug 13 20:04:53 2010
 Time Left: 11040 seconds

The <pre> can be used to maintain alignment.

Minimize changes to existing code:

 for k,v in string.gmatch(data, "(%w[%w ]*):%s*([%w%p ]+)\n") do t[k] = v end 
  • changed the first capture to (%w[%w ]*) to avoid spaces and get a space in Time Left
  • added %s* after : to avoid gaps in captured values
  • changed %s to a space in the second capture to avoid the capture \n
  • gmath fixed typos before gmatch and added ) to capture
+2
source

The sample below should work for you, provided that:

  • IP address is dotted decimal notation.
  • The MAC address is hexadecimal, separated by colons.

Note. The MAC address provided in your question has a β€œG” which is not a hexadecimal digit.

Edit: Thinking about your question in detail, I expanded my answer to show how multiple instances can be captured in a table.

 sString = [[ IP: 192.168.128.16 MAC: AF:3F:9F:c9:32:2E Expires: Fri Aug 1 20:04:53 2010 Time Left: 11040 seconds IP: 192.168.128.124 MAC: 1F:3F:9F:c9:32:2E Expires: Fri Aug 3 02:04:53 2010 Time Left: 1140 seconds IP: 192.168.128.12 MAC: 6F:3F:9F:c9:32:2E Expires: Fri Aug 15 18:04:53 2010 Time Left: 110 seconds ]] local tMatches = {} for sIP, sMac, sDate, sSec in sString:gmatch("IP:%s([%d+\.]+)%sMAC:%s([%x+:]+)%sExpires:%s(.-)%sTime%sLeft:%s(%d+)%s%w+") do if sIP and sMac and sDate and sSec then print("Matched!\n" .."IP: "..sIP.."\n" .."MAC: "..sMac.."\n" .."Date: "..sDate.."\n" .."Time: "..sSec.."\n") table.insert(tMatches, { ["IP"]=sIP, ["MAC"]=sMac, ["Date"]=sDate, ["Expires"]=sSec }) end end print("Total Matches: "..table.maxn(tMatches)) for k,v in ipairs(tMatches) do print("IP Address: "..v["IP"]) end 
+1
source

All Articles