Lua 中的 n 位模式匹配
我是 Lua 新手。
假设我有一个字符串“1234567890”。
我想迭代所有可能的三位数。 (即123,234,345,456....
)
for m in string.gmatch("1234567890","%d%d%d") do
print (m)
end
但这给了我输出123,456,789
。
我应该使用什么样的模式?
其次,一个相关的问题,如何指定3位
号码? "%3d"
似乎不起作用。 "%d%d%d"
是唯一的方法吗?
注意:这没有标记为正则表达式
,因为 Lua 没有 RegExp。 (至少在本地)
提前致谢:)
更新: 正如 Amber 指出的那样,Lua 中不存在“重叠”匹配。而且,关于第二个查询,我现在陷入了使用 string.rep("%d",n) 的困境,因为 Lua 不支持固定的重复次数。
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 expression
because 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的,核心 Lua 不包含完整的正则表达式。
string
模块理解的模式更简单,但足以满足很多情况。不幸的是,匹配重叠的 n 位数字并不是其中之一。也就是说,您可以手动迭代字符串的长度并尝试在每个位置进行匹配,因为 string.match 函数采用起始索引。例如:
这会产生以下输出:
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:This produces the following output:
gmatch
永远不会返回重叠匹配(并且gsub
永远不会替换重叠匹配,fwiw)。最好的选择可能是迭代所有可能的长度为 3 的子字符串,检查每个子字符串以查看它们是否与 3 位数字的模式匹配,如果是,则对它们进行操作。
(是的,
%d%d%d
是唯一的编写方式。Lua 的缩写模式支持没有固定重复次数的语法。)gmatch
never returns overlapping matches (andgsub
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.)