The Oddler
The Oddler

Reputation: 6698

Lua iterate over letter-number pairs from string?

I have a string that has a format like: "a3b12a5g625". First a letter and then a number. There can be any number of these pairs, from 1 to a whole lot.

I'm quite new to lua, and I'm trying to iterate over these pairs. How can this be done?

Upvotes: 2

Views: 541

Answers (2)

lhf
lhf

Reputation: 72312

If you want the pairs separate, then use

local str = "a3b12a5g625"
for a,b in string.gmatch(str, "(%a+)(%d+)") do
    print(a,b)
end

Upvotes: 4

user142162
user142162

Reputation:

You can use string.gmatch with the pattern: %a+%d+:

local str = "a3b12a5g625"
for pair in string.gmatch(str, "%a+%d+") do
    print(pair)
end

Output:

a3
b12
a5
g625

If you would like the numbers and letters split into separate variables, wrap each pattern item in a capture group:

local str = "a3b12a5g625"
for letters, numbers in string.gmatch(str, "(%a+)(%d+)") do
    print(letters, " ", numbers)
end

Output:

a       3
b       12
a       5
g       625

Upvotes: 3

Related Questions