I'm trying to understand how to split a string in lua with this format
hello - mynameis - jeff
I simply want to get the name "jeff". The delimiter will be an -
and a .
This is what I actually tried:
local result = string.gmatch(line, "[-\s]+")
Which doesn't work. How would I do it?
One of a workarounds can be replacing all " - " with a character that is not used in the content you have, and then get the last part with a simple negated character class with a $
end-of-string anchor:
local example = "hello - mynameis - jeff"
example = string.gsub(example, " %- ", "\x02")
local result = string.match(example, "[^\x02]+$")
print(result)
See the Lua IDEONE demo
With " %- "
, all space
+ -
+ space
substrings are replace with the temporary character, and then only the substring after the last temporary character is matched with [^\x02]+$
pattern.
I used the STX
control character (\x02
), but you may choose another that you are sure will be missing in the contents to parse.