有困难想出正则表达式。

我在 Lua 5.0 中遇到了两个场景,无法想出一个正则表达式来匹配这两个场景。

1)表达式 ="[^V]Core %d+:%s*%+(%d+%.%d+)°C %(crit = %+(%d+%.%d+)°C%)" 这可以正确匹配这个字符串:

Core 0:      +45.0°C  (crit = +100.0°C)

2)表达式 ="[^V]Core %d+:%s*%+(%d+%.%d+)°C %(high = %+%d+%.%d+°C, crit = %+(%d+%.%d+)°C%)" 这可以正确匹配这个字符串:

Core 0:      +45.0°C  (high = +86.0°C, crit = +100.0°C)

但是,我想能匹配两个字符串并捕获两个内容:第一个温度和临界温度。(我不需要高温度)。 我尝试了下面的正则表达式但不成功:

expression = "[^V]Core %d+:%s*%+(%d+%.%d+)°C  %((?:high = %+%d+%.%d+°C, )crit = %+(%d+%.%d+)°C%)"

我使用的是 Lua,但我认为正则表达式语法与其他语言(如 Perl)非常接近。 有任何想法吗?

原文链接 https://stackoverflow.com/questions/5274737

点赞
stackoverflow用户582206
stackoverflow用户582206

我认为在 (?:...) 分组后面需要一个 ?

还有一些有趣的事情发生在括号之前的空格数量上——字符串和不起作用的正则表达式有两个空格,而“有效”的正则表达式只有一个。为了保持健壮性,我建议在那里使用 %s+

2011-03-11 15:41:32
stackoverflow用户221509
stackoverflow用户221509

Lua 字符串 patterns 不是 _正则表达式_。

为了做你想要的事情——匹配两个不同的字符串——你需要实际尝试两个匹配。

local input = ... -- 输入字符串
-- 尝试第一个模式
local temp, crit = string.match(input, "[^V]Core %d+:%s*%+(%d+%.%d+)°C %(crit = %+(%d+%.%d+)°C%)"
-- 如果没有匹配成功,尝试第二个匹配
if not temp then
    temp, crit = string.match(input, "[^V]Core %d+:%s*%+(%d+%.%d+)°C  %(high = %+%d+%.%d+°C, crit = %+(%d+%.%d+)°C%)")
end
if temp then
    -- 两个匹配中的一个保存在 temp 和 crit 中
    -- 在这里进行有用的操作
end
2011-03-12 18:19:02