Regular expressions in Lua using .gsub()

10,238

Solution 1

Lua doesn't use regular expressions. See Programming in Lua, sections 20.1 and following to understand how pattern matching and replacement works in Lua and where it differs from regular expressions.

In your case you're replacing the complete string (.*) by the literal string .* – it's no surprise that you're getting just .* returned.

The original regular expression replaced anything containing a colon (.*:(.*)) by the part after the colon, so a similar statement in Lua might be

string.gsub(Mem, ".*:(.*)", "%1")

Solution 2

The code below parses the contents of that file and puts it in a table:

meminfo={}
for Line in io.lines("/proc/meminfo") do
    local k,v=Line:match("(.-): *(%d+)")
    if k~=nil and v~=nil then meminfo[k]=tonumber(v) end
end

You can then just do

print(meminfo.MemTotal)
Share:
10,238

Related videos on Youtube

OddCore
Author by

OddCore

Updated on June 04, 2022

Comments

  • OddCore
    OddCore almost 2 years

    Ok, I think I overcomplicated things and now I'm lost. Basically, I need to translate this, from Perl to Lua:

    my $mem;
    my $memfree;
    open(FILE, 'proc/meminfo');
    while (<FILE>)
    {
        if (m/MemTotal/)
        {
            $mem = $_;
            $mem =~ s/.*:(.*)/$1/;
        }
    
    }
    close(FILE);
    

    So far I've written this:

    for Line in io.lines("/proc/meminfo") do
        if Line:find("MemTotal") then
            Mem = Line
            Mem = string.gsub(Mem, ".*", ".*", 1)
        end
    end
    

    But it is obviously wrong. What am I not getting? I understand why it is wrong, and what it is actually doing and why when I do

    print(Mem)
    

    it returns

    .*
    

    but I don't understand what is the proper way to do it. Regular expressions confuse me!

  • OddCore
    OddCore almost 14 years
    ok, thank you. It sort of makes sense now, I just think I will never be able to fully comprehend regular expressions.
  • sedavidw
    sedavidw almost 14 years
    The capture group ((.*)) is unnecessary. string.gsub(Mem, ".*:", "") is enough. It removes everything up to the last :.
  • Rich
    Rich almost 14 years
    @Mizard: I just copied the code verbatim from the Perl code, but indeed this should suffice, yes.
  • daurnimator
    daurnimator almost 14 years
    This is a much better and more complete solution.