How do you get digit of a letter or number in a string?

I have “11221232122” string but I need find this string “3” which digit.
I using this:

local stringis = "11221232122"
for i=1, string.len(stringis) do
if string.sub(stringis, i, i) == "3" then
local answer = i
end
end

but I want to use something simpler than this.
example:

local stringis = "11221232122"
local answer = string.matches(stringis, "3")
print(answer)

Output

7

You can use string.find which returns where this string was found.

print(string.find("11221232122", "3")) -- 7 7

string.find returns both where the match starts and where the match ends, since it’s just 1 character in this case it starts and ends at the same place.

1 Like

why its 7 7 , why not only 7 ?

string.find() returns where does the first match found starts and ends. Like in incapaz’s example, the pattern “3” is found at 7th character and ends at 7th character. If we change “3” to “321” it will return 7 9 because the specified pattern is first found at 7th character and continues to the 9th character in the string.

You might be wondering why this function returns another value that specifies where does the string pattern end since naturally you would know how long would be your string pattern be but this function also support character classes like %w (%w is used for matching alphanumeric characters.) unless specified otherwise by passing the 4th argument when firing the function to true.

Here is an example:

print(string.find("!+-hello/*//", "%w+")) --%w is used for only matching an alphanumeric character (Letters and numbers.). The "+" sign next to it is used to match at least 1 or more of the specified character class. Without the "+" sign it would output as "4 4".
--Output
-> 4 8
1 Like

can we make this:

local example = "12 45 23 6 944 204 21 54 91 4"
print(string.finding(example, " ", 1))
print(string.finding(example, " ", 2))
print(string.finding(example, " ", 5))
local answer = string.sub(example, tonumber(string.finding(example, " ", 1)) + 1, tonumber(string.finding(example, " ", 2)) - 1)
print(answer)

Output

3
6
15
45


string.finding(example, " ", <Which(example: 1. 5. 20. 11.)>))