Lua 中的模式匹配字符串
我使用 Lua 将以下字符串拆分为一个表: (数据是相互对齐的。我没有找到如何在这个网站上编写这样的格式)
IP:192.168.128.12
MAC: AF:3G:9F:c9:32:2E
到期时间:2010 年 8 月 13 日星期五 20:04:53
剩余时间:11040 秒
结果应放入如下表中:
t = {"IP" : "192.168.128.12", "MAC" : "AF:3G:9F:c9:32:2E", "过期" : "2010 年 8 月 13 日星期五 20:04:53", “剩余时间”:“11040 秒”}
我尝试过:
for k,v in string.gmatch(data, "([%w]+):([%w%p%s]+\n") do
t[k] = v
end
这是我最好的尝试。
I have the following string to split into a table using Lua:
(the data is aligned with each other. I did not find out how to write format it like that on this site)
IP: 192.168.128.12
MAC: AF:3G:9F:c9:32:2E
Expires: Fri Aug 13 20:04:53 2010
Time Left: 11040 seconds
the result should be put into a table like this:
t = {"IP" : "192.168.128.12", "MAC" : "AF:3G:9F:c9:32:2E", "Expires" : "Fri Aug 13 20:04:53 2010", "Time Left" : "11040 seconds"}
I tried with:
for k,v in string.gmatch(data, "([%w]+):([%w%p%s]+\n") do
t[k] = v
end
That was my best attempt.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解你的用例,以下应该可以解决问题。不过,它可能需要一些调整。
If I understood your use case the following should do the trick. It might require a bit of tweaking though.
假设“数据彼此对齐”意味着如下所示:
最大限度地减少对现有代码的更改:
Time Left
中获取空格(%w[%w ]*)
,以避免前导空格并在添加的:
之后的 %s*,以避免捕获值中的前导空格%s
更改为空格,以避免捕获\n
gmath
为gmatch
的拼写错误,并添加了)
用于捕获Assuming "data aligned with each other" means something like the following:
The
<pre>
tag can be used to maintain alignment.Minimizing changes to your existing code:
(%w[%w ]*)
, to avoid leading spaces and to get space inTime Left
%s*
after:
, to avoid leading spaces in captured values%s
to space in second capture, to avoid capturing\n
gmath
togmatch
and added)
for capture下面的模式应该适合您,前提是:
注意:您问题中提供的 MAC 地址有一个“G”,它不是十六进制数字。
编辑:详细考虑您的问题后,我扩展了我的答案,以展示如何将多个实例捕获到表中。
The pattern below should work for you, provided that:
Note: The MAC address provided in your question has a 'G' which is not a hexadecimal digit.
Edit: After thinking about your question in detail, I have expanded my answer to show how multiple instances can be captured into a table.