Lua 中使用 .gsub() 的正则表达式
好吧,我想我把事情变得过于复杂了,现在我迷路了。基本上,我需要将其从 Perl 翻译为 Lua:
my $mem;
my $memfree;
open(FILE, 'proc/meminfo');
while (<FILE>)
{
if (m/MemTotal/)
{
$mem = $_;
$mem =~ s/.*:(.*)/$1/;
}
}
close(FILE);
到目前为止我已经写了:
for Line in io.lines("/proc/meminfo") do
if Line:find("MemTotal") then
Mem = Line
Mem = string.gsub(Mem, ".*", ".*", 1)
end
end
但这显然是错误的。我没有得到什么?我明白为什么它是错误的,它实际上在做什么,为什么当我
print(Mem)
这样做时它会返回,
.*
但我不明白什么是正确的方法。正则表达式让我困惑!
Ok, I think I overcomplicated things and now I'm lost. Basically, I need to translate this, from Perl to Lua:
my $mem;
my $memfree;
open(FILE, 'proc/meminfo');
while (<FILE>)
{
if (m/MemTotal/)
{
$mem = $_;
$mem =~ s/.*:(.*)/$1/;
}
}
close(FILE);
So far I've written this:
for Line in io.lines("/proc/meminfo") do
if Line:find("MemTotal") then
Mem = Line
Mem = string.gsub(Mem, ".*", ".*", 1)
end
end
But it is obviously wrong. What am I not getting? I understand why it is wrong, and what it is actually doing and why when I do
print(Mem)
it returns
.*
but I don't understand what is the proper way to do it. Regular expressions confuse me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Lua 不使用正则表达式。请参阅《Lua 编程》的 20.1 部分以及后面的部分,了解模式匹配和替换在 Lua 中的工作原理。 Lua 以及它与正则表达式的不同之处。
在您的情况下,您将完整的字符串 (
.*
) 替换为文字字符串.*
- 毫不奇怪,您只得到.*< /代码> 返回。
原来的正则表达式用冒号后面的部分替换了任何包含冒号(
.*:(.*)
)的内容,因此 Lua 中的类似语句可能是Lua doesn't use regular expressions. See Programming in Lua, sections 20.1 and following to understand how pattern matching and replacement works in Lua and where it differs from regular expressions.
In your case you're replacing the complete string (
.*
) by the literal string.*
– it's no surprise that you're getting just.*
returned.The original regular expression replaced anything containing a colon (
.*:(.*)
) by the part after the colon, so a similar statement in Lua might be下面的代码解析该文件的内容并将其放入表中:
然后您可以执行以下操作
The code below parses the contents of that file and puts it in a table:
You can then just do