What’s the most effective way to ‘cut off’ the last word in a string?
For example:
"Standard Car Red"
to
"Standard Car"
What’s the most effective way to ‘cut off’ the last word in a string?
For example:
"Standard Car Red"
to
"Standard Car"
If you define a “word” as a string of non-space characters then %S+
will match it, and the $
anchor will ensure it is at the end of the string.
local s = ("Standard Car Red"):gsub("%S+$", "")
print(s)
The result will be "Standard Car "
; if you want to get rid of the extra space(s) before the last word then include %s*
in the pattern: %s*%S+$
If a “word” is only a string of alphanumeric characters then %w+
will match it, and (%W*)
will capture the rest of the string after it, like punctuation, and %1
in gsub’s replace argument will reference the captured string.
local s = ("Standard Car Red.-=[];,/"):gsub("%s*%w+(%W*)$", "%1")
print(s)
results in "Standard Car.-=[];,/"
That’s great, thank you.
What’s the best way to go about learning this? I know Roblox have a page on string manipulation but I can’t find anything on ‘%S+’, '$", etc
The DevHub search doesn’t work very well; not surprised you couldn’t find it.
Perfect, thanks!
The lua 5.1 manual describes the pattern matching language
https://www.lua.org/manual/5.1/manual.html#5.4.1
“Programming in Lua” also has sections on patterns and captures
https://www.lua.org/pil/20.2.html
https://www.lua.org/pil/20.3.html
https://www.lua.org/pil/20.4.html