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

Don't know which string pattern to use?

Asked by 9 years ago
local str = "workspace.Some Stupid Name With Spaces.Part" -- This is an example. No, it's not "workspace['Some Stupid Name With Spaces'].Part"

I need to find workspace, Some Stupid Name With Spaces and Part using the string.gmatch function.

Code I used, which ALMOST works:

local pattern = "%w+"
for w in str:gmatch(pattern) do
    print(w)
end

That code above only works if the string doesn't have spaces in it.

So, what do I need to do to make it work?

1 answer

Log in to vote
1
Answered by
Unclear 1776 Moderation Voter
9 years ago
local pattern = "[^%.]+"

That string pattern will do.

It's rather simple. You basically want to split the string up based around the . character. This character is known as our delimiter.

The first thing we want to do is figure out how to represent our delimiter in a string pattern. For ., you need to escape it since it is a magic character. This can be done with the % character, so you would represent . by using %.. This is because . already means something in Lua's string pattern system, so you need to indicate that you mean the raw character.

By itself, %. just isolates all of the . characters in our string. We want the opposite: we want all of the non . characters. This can be done with the ^ character, which switches whatever pattern it is in front of to get the compliment. This means that if we do ^%., then we get the opposite of %.; essentially, it will get all non . characters for us.

We're not done yet, though. We want to keep all of the non . characters together; as it stands right now, ^%. only gives us each individual character. This can be done with the + character, which gives us strings matching one or more repetitions of the pattern behind it. However, it isn't as simple as just tacking it behind our pattern. Notice how if you do ^%.+, the pattern that + is paired to is ., not ^%. as we expected.

For these cases, I like using the [] characters, which form a new character set for you based upon a pattern inside of the brackets. For example, [^%.] will match all non . characters, but only one at a time, just like what was inside of it. However, + works with these custom character sets! So, we can do [^%.]+, and + will be associated with [^%.], which is exactly what we want.

0
Solid answer. Thought me about the ^ character as well! (didn't really understand it on the wiki) Vlatkovski 320 — 9y
Ad

Answer this question