lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Aaron Brown wrote:
One problem with Shmuel's solution quoted above is that it
treats the first of the above two strings as four lines, the
last being empty.  If you want to treat both of them as
three lines, you need to do something like this:

 if string.sub(Str, -1) ~= "\n" then
   -- The last line doesn't have an EOL; give it one:
   Str = Str .. "\n"
 end
 for Line in Str:gmatch("([^\n]*)\n") do
   print("line: <" .. Line .. ">")
 end

or this (doesn't side-effect Str):

 local MissingEol = false
 if string.sub(Str, -1) ~= "\n" then
   -- The last line doesn't have an EOL; give it one:
   MissingEol = true
 end
 for Line in (MissingEol and Str .. "\n" or Str):gmatch("([^\n]*)\n") do
   print("line: " .. Line)
 end

This is impossible to do with just a single pattern and no
additional checks, but using string.sub avoids a linear scan
of the string.  (In other words, don't use Str:match("\n$").)

Nice examples and explanation, though the original poster said explicitly he wanted "an expression that needs no additional checks".

Regarding the "impossible to do with just a single pattern", yes, with Lua regex, but it IS possible with Lrexlib PCRE binding:

  for line in rex.gmatch (str, "^.*", "m")
    do print(line)
  end

(the 3-rd argument "m" stands for "multiline" PCRE option)


--
Shmuel