Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to get items that all start with the same word?

Asked by 7 years ago

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?

2 answers

Log in to vote
0
Answered by 7 years ago

Anchor

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 ^

Matching

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.

Application

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.

Ad
Log in to vote
-1
Answered by 7 years ago
Edited 7 years ago
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.

0
doesn't string.match look for the string in that name not the start of the name? So I suggest doing ' if string.sub(str, 1, 5) == "Hello" then' thesit123 509 — 7y
0
Change the number 5 to the length of the starting name. thesit123 509 — 7y

Answer this question