Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 967
Red-Cloud Avatar asked Feb 07 '26 01:02

Red-Cloud


2 Answers

function getStrPart(str,n) -- return a substring
  if n>=0 then
    return (
      str:gsub("!.*", "%0!")
         :gsub("[^!]*!", "", n)
         :match("^([^!]*)!")
    )
  end
end
like image 110
Egor Skriptunoff Avatar answered Feb 09 '26 01:02

Egor Skriptunoff


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
like image 35
Nicol Bolas Avatar answered Feb 09 '26 00:02

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!