开发者

n-digit Pattern Matching in Lua

I'm new to Lua.

Say i have a string "1234567890".

I want开发者_StackOverflow 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.


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.)


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
>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜