Hey,
I have a couple of strings, [00]_[ui_actions]_[123]_[outline]_135
and [00]_[ui_actions]_[abc]_[outline]_1.
I’d like to remove the last few numbers.
However, the problem comes as the strings contain the identifier and sometimes contains a number as the name ([00]) and ([123]). This means that removing all numbers isn’t possible. I’ve also tried using string.split("_")[8 or 7 or 6] however, it would sometimes return as nil.
Could you take a step back and explain why you’re trying to do this? Answering your literal question is possible but I feel like there’s probably a better solution to accomplish whatever your task is that might not involve string manipulation in the first place.
function removeLastNumbersFromStringSeparatedByUnderscores(str)
local strings = str:split("_")
local newStr = ""
for i, theThingYouHaveInBrackets in pairs(strings) do
if i == #strings and tonumber(theThingYouHaveInBrackets) then break end
newStr = newStr.. "_" ..theThingYouHaveInBrackets
end
return newStr
end
local String1 = "[00]_[ui_actions]_[123]_[outline]_135"
local String2 = "[00]_[ui_actions]_[abc]_[outline]"
function RemoveFinalNumbers(str)
local Filtered = string.gsub(str, "%d*$", "")
local LastCharacter = str:sub(#str, #str)
if LastCharacter == "_" then
Filtered = Filtered:sub(1,Filtered:len()-1)
end
return Filtered
end
print(RemoveFinalNumbers(String1))
print(RemoveFinalNumbers(String2))