Remove all characters from a string but letters and numbers

I’m looking for a method to remove all characters but "0-9" and "Aa-Zz" in a string.

EX:

"Test-01.2" = "Test012"

I’ve tried looking this up on the forums and the Lua API, however I haven’t found anything that suits this, and I’m confused on the Lua API page.

After giving String Patterns a quick read you should be able to do string.gsub() with %W as the second argument

Code:

print(string.gsub("Test-01.2","%W",""))
print(string.gsub("Test-01.2","%w",""))

Expected Output

Test012 2
-. 7

The numbers on the right are the amount of characters replaced and are not part of the string

2 Likes

Thanks for clarifying that, that was one of the issues in my methods! However whenever I set the attribute of the new string, it removes everything but alphabetical characters.

image

test1 is the string I manually set.
"helloworld" was suppose to be "helloworld2" | translated from "hello.world2"

Update, the module I was printing it through was cached since I was running this though command line.

If you’re looking to use the module code:

function module:subNonStringCharacters(str)
	if typeof(str) == "string" then
		local newString, replacedCharacters = string.gsub(str,"%W","");
		return  newString
	end
end;