Hello! I was wondering if this was possible. Say you have multiple parts that start with the same word, but end in a different letter. How would you get all of them?
You can use an anchor, which is a special character in pattern matching that only completes one iteration. In other words, it only makes one attempt to look for your match at the beginning of the string. The anchor is represented by the circumflex accent character ^
Now we can use this anchor in our match
function to look only at the start of a string. Here's an example:
print(string.match("hello world, how are you?", "^hello"))
The second argument (the pattern, or whatever we're looking for in the string) is telling the program to look at the beginning of the string to find a match for hello
- which it does. You can differentiate this from an example that doesn't use an anchor as follows...
print(string.match("world, hello how are you?", "^hello")) -- > nil print(string.match("world, hello how are you?", "hello")) -- > "hello"
As you can see, the anchor makes a big difference, as it's very explicit. Whereas without the anchor, match
will iterate over the all the characters in the string looking for a match in any arbitrary location.
Applying this to your application would be equally as simple...
local function containsFirstWord(array, word) for i = 1, #array do local v = array[i] if string.match(v, "^"..word) then return true, v end end end containsFirstWord({ "goodbye friends"; "hello friends"; "friends, hello"; "friends, goodbye"; }, "hello") -- > true, "hello friends"
If you have any questions, just leave a comment and I'll get back to you as soon as possible.
for i,v in pairs(game.Workspace:GetChildren()) do if v:IsA("Part") then str = v.Name if string.match(str, "Hello") then print ("The word Hello was found.") else print ("The word Hello was not found.") end end end
This will print out "The word Hello was found" if it finds a part that has the word Hello in it.