I would like to find out if a string contains a certain word, and word only. Currently everything I find online uses .match or .find but here is the issue I am having with these, these will for example, check if a string contains “hi” which works great if the person says something like, “hi hru” but doesn’t work out so well if someone says “high” or “ship” as it still detects it having “hi” in it. Is there a way to only detect stand alone words?
Any help is appreciated, thanks!
[Edit]
Anyone who has this problem, here is the line I used to detect someone saying “hi”, you could add more to it if you want it to detect punctuation but I don’t need that for my purposes.
local msg = msg:lower()
if string.find(msg, "[%s]hi[%s]") or string.find(string.sub(msg, #msg-2, #msg), "[%s]hi") or string.find(string.sub(msg, 1, 3), "hi[%s]") or msg == "hi" then
print("found hi!")
end
I admit this might be a clunky way of doing this, but it is the best I could do, thanks!
The simplest and easiest solution may be to do this. Instead of searching for the word "hi" try searching for the word " hi ", with spaces before and after, ensuring that it is a standalone word.
Problems may arise, however. For example, you may have the sentence “My friend said hi.” where there is a period after the word “Hi.” Because of this, you may have to search for multiple strings, which would include the word with a period after it, with spaces before and after it, and with a comma after it.
This is just the first approach I thought of, and I bet you can find a better solution if you need to think of every single possible sentence and string structure. But other than that, feel free to go ahead and work off of this idea
Thanks!
I thought of this type of solution but I had one problem arise, what if the player just says “hi” and nothing else? Is there anyway to detect if its a “hi” with nothing on a side of it. Maybe something like “hi{Nothing}” (Obviously that example wouldn’t work but is there any way to detect that in a string?)
I was more trying to get at other situations such as someone saying, "HKFJDShi " it would be nice to be able to do, "{Nothing}hi " as then you could truly detect if this was the start of the message. If this isn’t possible, which I assume it isn’t is there anyway to detect if something starts or ends a string? Would something like this work, string:sub("hi hru", 1, 2) == "hi" then and to end a string string:sub("hru hi", strLength-1, strLength)
Roblox’s string.find takes a pattern, which can do a lot of crazy stuff!. To find whole words try string.find(my_string, "[^%a]hi[^%a]").
It is a very arcane feature, regular expressions are often regarded as the most misunderstood programming language. You can read more about lua’s pattern matching here