How Would I Remove The Last Numbers From A String?

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.

Are there any other solutions?

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.

this is the simplest way i could think of

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
	return newStr

I’m confused why not just

local s = "[00]_[ui_actions]_[123]_[outline]_135"

local stripped = string.gsub(s, "%d*$", "")


My original question still stands tho

Attempt this method

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)
	return Filtered

1 Like

This would error, len needs to be called via the colon operator.

local String1 = "[00]_[ui_actions]_[123]_[outline]_135"
local String2 = "[00]_[ui_actions]_[abc]_[outline]"

print(string.gsub(String1, "_?%d+$", "")) --[00]_[ui_actions]_[123]_[outline] 1 (1 replacement made).
print(string.gsub(String2, "_?%d+$", "")) --[00]_[ui_actions]_[abc]_[outline] 0 (0 replacements made).
1 Like