How can I find a number within text?

Just curious, let’s say there is a sentence, “Bob ate 5 cookies.” How can I find the number in this sentence (5), and always print the numbers regardless of their value?

More than one way, depending on your use case.

local str = "Bob ate 50 cookies"

print(string.match(str, "%d+")) --> 50 (string)
print(string.split(str, " ")[3]) --> 50 (string)
-- ...
  • Option one returns the first capture of a sequence of digits, e.g. in “10 and 20” it would return “10”.

  • Option two splits a string at each occurance of a whitespace. We know the number is the third string, so we read the value in the table at index 3.

  • For getting all number captures, there is gmatch - which returns an interator - with the same pattern (“%d+”).

1 Like

Thanks! Do you know how to convert a value to a number?
localplr.Character.Humanoid.WalkSpeed=tonumber(string.split(msg, " ")[3])

oh wait nvm, I just used the first one and it works fine.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.