Get part of a string

Asked

Viewed 130 times

2

I am going to fetch some data from a file in ics format. The problem is that the file can change several times. I have this code to put in each variable each data of a certain line in the file. Example:

     for line in f:lines() do 
       f line:sub(1,5) == "RRULE" then --objet
            rule = line

            freq = string.match(rule,"FREQ=(.*);")
            until_ = string.match(rule,"UNTIL=(.*)")
            interval = string.match(rule,"INTERVAL=(.*)")
            count = string.match(rule,"COUNT=(.*)")
        end
      end

And these are the many examples of the file line I can get:

RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5

RRULE:FREQ=DAILY;INTERVAL=2

RRULE:FREQ=DAILY;UNTIL=19971224T000000Z

How can I get to put in each different variable?

  • What’s the matter?

  • I want to get each parameter of the RRULE line in each variable. For example get the "DAILY" in the freq variable. My problem is that not everyone always ends up with one ;

  • What are the various tabs in your file?

  • The line separators are the point and comma. But using the various examples of the RRULE lines, my code does not work correctly.

  • You can for an example run showing exactly how it works and what is going wrong?

1 answer

1


The problem with your code is the use of .*, which is a greedy pattern, that is, take all from that point on.

Here is a robust way to pick up all the fields of a line, whatever the order in which they appear:

for line in f:lines() do 
    if line:sub(1,5) == "RRULE" then
        local t={}
        line=line..";"
        for k,v in line:gmatch("(%w-)=(.-);") do
            t[k]=v
        end
        -- check that we have parsed the line correctly
        print(line)
        for k,v in pairs(t) do
            print(k,v)
        end
    end
end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.