views:

38

answers:

1

I am trying to understand what the difference is between string.find and string.match in Lua. To me it seems that both find a pattern in a string. But what is the difference? And how do I use each? Say, if I had the string "Disk Space: 3000 kB" and I wanted to extract the '3000' out of it.

EDIT: 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/;
    }
    elseif (m/MemFree/)
    {
        $memfree = $_;
        $memfree =~ 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!

+1  A: 

In your case, you want string.match:

local space = tonumber(("Disk Space 3000 kB"):match("Disk Space ([%.,%d]+) kB"))

string.find is slightly different, in that before returning any captures, it returns the start and end index of the substring found. When no captures are present, string.match will return the entire string matched, while string.find simply won't return anything past the second return value. string.find also lets you search the string without being aware of Lua patterns, by using the 'plain' parameter.

Use string.match when you want the matched captures, and string.find when you want the substring's position, or when you want both the position and captures.

Ok, thank you, I understand now. In my textbook it defined string.find(subject string, pattern string, optional start position, optional plain flag).As I understand it, optional start position is the position that we might like the search to start, not an output variable that returns the position of the pattern we are looking for. Or is it? Cause otherwise I just didn't notice that a position was being returned in my textbook examples and I apologise.
OddCore
The start position parameter specifies where in the string to start searching. You can use it for both string.match and string.find.