views:

52

answers:

2

I'm new to Lua.

Say i have a string "1234567890".

I want to iterate over all possible 3 digit numbers. (ie 123,234,345,456....)

for m in string.gmatch("1234567890","%d%d%d") do
      print (m)
end

But this gives me the output 123,456,789.

What kind of Pattern should i be using?

And secondly, a related question, how do i specify a 3-digit number? "%3d" doesn't seem to work. Is "%d%d%d" the only way?

Note: This isn't tagged Regular expressionbecause Lua doesn't have RegExp. (atleast natively)

Thanks in advance :)

Update: As Amber Points out, there is no "overlapping" matches in Lua. And, about the second query, i'm now stuck using string.rep("%d",n) since Lua doesn't support fixed number of repeats.

+1  A: 

gmatch never returns overlapping matches (and gsub never replaces overlapping matches, fwiw).

Your best bet would probably be to iterate through all possible length-3 substrings, check each to see if they match the pattern for a 3-digit number, and if so, operate on them.

(And yes, %d%d%d is the only way to write it. Lua's abbreviated patterns support doesn't have a fixed-number-of-repetitions syntax.)

Amber
@Amber, Thank you, That's unfortunate! Do you have any idea about a simpler n-digit pattern? :)
st0le
Hey, as I edited my answer to mention, Lua's simplistic pattern matching doesn't have a simpler syntax.
Amber
@Amber, I've already done that...:) but i thought maybe i should go for a more "Lua-ish" Solution. :)
st0le
+1  A: 

You are correct that core Lua does not include full regular expressions. The patterns understood by the string module are simpler, but sufficient for a lot of cases. Matching overlapping n-digit numbers, unfortunately, isn't one of them.

That said, you can manually iterate over the string's length and attempt the match at each position since the string.match function takes a starting index. For example:

s = "1234567890"
for i=1,#s do
    m = s:match("%d%d%d", i)
    if m then print(m) end
end

This produces the following output:

C:>Lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> s = "1234567890"
> for i=1,#s do
>>     m = s:match("%d%d%d", i)
>>     if m then print(m) end
>> end
123
234
345
456
567
678
789
890
>
RBerteig