Regular expressions in Lua using .gsub()
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)
Related videos on Youtube
OddCore
Updated on June 04, 2022Comments
-
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 almost 14 yearsok, thank you. It sort of makes sense now, I just think I will never be able to fully comprehend regular expressions.
-
sedavidw almost 14 yearsThe capture group (
(.*)
) is unnecessary.string.gsub(Mem, ".*:", "")
is enough. It removes everything up to the last:
. -
Rich almost 14 years@Mizard: I just copied the code verbatim from the Perl code, but indeed this should suffice, yes.
-
daurnimator almost 14 yearsThis is a much better and more complete solution.