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

String pattern help?

Asked by
LuaQuest 450 Moderation Voter
8 years ago

Just wondering, how could i conduct a string pattern that captures every 5 characters in a string (no matter that they are)? I know getting every character in a string is done like this:

for c in string.gmatch("hello*world*", ".") do
    print(c)
end

-- h
-- e
-- l
-- l
-- o
-- *
-- w
-- ...

But how would i make it so it would split the string every 5 characters? Including all kinds, like spaces, symbols, ect. So the output from above would instead look something like this:

-- hello      -- (cut at 5)
-- *worl     -- (cut at next 5)
-- d*            -- (cut from last 5, to end)

If someone knows how this could work, and is willing to share, I'd appreciate it very much. Thanks.

1 answer

Log in to vote
3
Answered by
Unclear 1776 Moderation Voter
8 years ago

Use the . character. This character in a string pattern represents any character.

Your pattern would therefore be ..... (five . characters).

local phrase = "hello*world*"
for match in phrase:gmatch(".....") do
    print(match)
end

However, this does not get the last portion. You will have to retrieve that with the sub method. A simple formula is to subtract the remainder of the phrase, add one, and start the substring from there. You can do this with the modulus operator %.

print(phrase:sub(#phrase - #phrase%5 + 1))
0
Thank you very much. LuaQuest 450 — 8y
Ad

Answer this question