Red-Cloud
Red-Cloud

Reputation: 458

Lua: substrings

I have a string which can be of any characters. I like to extract only the part between two exclamation marks or before the first or after the last one:

str = "what)ever!when(ver!time!is!mo/ey"

function getStrPart(str,n) -- return a substring
  return str:sub(...) or nil
end

getStrPart(str,0) -- return "what)ever"  -- string until the first !
getStrPart(str,1) -- return "when(ver"   --  between first and second !
getStrPart(str,2) -- return "time"
getStrPart(str,3) -- return "is"
getStrPart(str,4) -- return "mo/ey"
getStrPart(str,5) -- return nil    -- for all n less 0 or > 4 (no of the !)

If the string contains no !

str = "whatever"  

then the function should return nil

Upvotes: 3

Views: 2514

Answers (2)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23767

function getStrPart(str,n) -- return a substring
  if n>=0 then
    return (
      str:gsub("!.*", "%0!")
         :gsub("[^!]*!", "", n)
         :match("^([^!]*)!")
    )
  end
end

Upvotes: 2

Nicol Bolas
Nicol Bolas

Reputation: 474436

Your getStrPart function is going to be highly inefficient. Every time you call it, you have to search through the whole string. It would be much better to just return a table containing all of the "string parts" that you index.

Also, Lua uses 1-based indices, so you should stick to that too.

function get_string_parts(str)
  local ret = {}
  for match in str:gmatch("[^!]") do
    if(#match == #str) then --No `!` found in string.
      return ret
    end
    ret[#ret + 1] = match
  end
  return ret
end

Upvotes: 2

Related Questions