How would I get all the numbers in a string?

How would I get all the numbers that are in a string? Tonumber returns nil if there are any characters but numbers in the string (pretty sure).

3 Likes

You can use:

local numbers = print(string.gsub("hello123hi", "%D", ""))
print(numbers) --123

--%D selects all characters except numbers, and "" replaces them with nothing

string.gsub allows you to replace all characters that match with the pattern (%D) with the replacing string, i.e. “” (nothing).

Refer to this for more string references.

32 Likes

Something to be aware of is that this will also strip negative numbers of their “-” sign and decimal numbers of their decimal point.

7 Likes

You can also use this to get the individual digits:

local word = "a50td@"
for digit in (string.gmatch(word,"%d")) do
    print(digit)
end
3 Likes

Alright so I ran into a problem.

print(string.gsub("$122,22", "%D", ""))

This prints

12222 2

It looks like it prints an extra " 2" at the end, why is this happening?

The 2 at the end is the total matches found, in this case “$” and “,”.

2 Likes