Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua gmatch store captured groups as an array

I'm rather new to Lua. For each match of gmatch, I would like to put the capture group results into an array.

The idea is so I get all the capture groups for each match, as an array, so I can do operations on this array, e.g. convert each capture group to an int.

How would I change the following, so it prints 3 2 1?

function split_ipv4(str)
    for parts in str:gmatch('(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?), ') do
       print(parts[4])
    end
end

split_ipv4('192.168.0.3, 192.168.0.2, 192.168.0.1')

Changing parts to p1, p2, p3, p4 and printing p4 works, but is there a way of not creating a variable for each group?

like image 906
simonzack Avatar asked Mar 31 '26 04:03

simonzack


1 Answers

The most simple way is to change parts to p1, p2, p3, p4
But in case of variable-phobia:

function split_ipv4(str)
   for addr in str:gmatch'%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?' do
      local parts = {addr:match'(%d+)%.(%d+)%.(%d+)%.(%d+)'}
      print(parts[4])
    end
end

split_ipv4('192.168.0.3, 192.168.0.2, 192.168.0.1')
like image 197
Egor Skriptunoff Avatar answered Apr 02 '26 20:04

Egor Skriptunoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!