5

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.

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
st0le
  • 33,375
  • 8
  • 89
  • 89
  • 3
    `("%d"):rep(n)` is a slightly more idiomatic way to write the call to `string.rep`. It works because `string` is the metatable for all string values by default. – RBerteig Oct 17 '10 at 22:03

2 Answers2

5

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
  • 41,948
  • 7
  • 88
  • 128
4

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
  • 507,862
  • 82
  • 626
  • 550
  • Thank you, That's unfortunate! Do you have any idea about a simpler n-digit pattern? :) – st0le Oct 17 '10 at 07:23
  • Hey, as I edited my answer to mention, Lua's simplistic pattern matching doesn't have a simpler syntax. – Amber Oct 17 '10 at 07:24
  • I've already done that...:) but i thought maybe i should go for a more "Lua-ish" Solution. :) – st0le Oct 17 '10 at 07:24