Lua string.match使用不规则的正则表达式?

时间:2011-08-21 12:13:59

标签: regex lua

我很好奇为什么这不起作用,需要知道为什么/如何解决它;我正在尝试检测某些输入是否是一个问题,我很确定string.match是我需要的,但是:

print(string.match("how much wood?", "(how|who|what|where|why|when).*\\?"))

返回nil。我pretty sure Lua's string.match uses regular expressions在字符串中找到匹配项,因为我在成功之前使用过通配符(。),但也许我不了解所有的机制? Lua在字符串函数中是否需要特殊的分隔符?我已经测试了我的正则表达式here,所以如果Lua使用常规正则表达式,上面的代码似乎会返回"how much wood?"

你能否告诉我我做错了什么,我的意思是什么,或者指出一个很好的参考资料,我可以获得有关Lua的字符串操作函数如何利用正则表达式的全面信息?

3 个答案:

答案 0 :(得分:13)

Lua不使用正则表达式。 Lua使用Patterns,它看起来相似但匹配不同的输入。

.*也将消耗输入的最后?,因此它在\\?上失败。问号应排除在外。使用%转义特殊字符。

"how[^?]*%?"

正如Omri Barel所说,没有交替运营商。您可能需要使用多个模式,一个用于句子开头的每个替代单词。或者您可以使用支持正则表达式的库。

答案 1 :(得分:9)

根据manual,模式不支持交替。

因此"how.*"工作时,"(how|what).*"不会。

kapep对.*吞下的问号是正确的。

有一个相关问题:Lua pattern matching vs. regular expressions

答案 2 :(得分:0)

正如他们之前已经回答的那样,这是因为lua中的模式与其他语言中的Regex不同,但是,如果您尚未设法获得一个可以完成所有工作的良好模式,则可以尝试使用此简单功能:

local function capture_answer(text)
  local text = text:lower()
  local pattern = '([how]?[who]?[what]?[where]?[why]?[when]?[would]?.+%?)'
  for capture in string.gmatch(text, pattern) do
    return capture
  end
end

print(capture_answer("how much wood?"))

Output: how much wood?

如果您想在较大的文本字符串中查找问题,该功能也将为您提供帮助

例如。

print(capture_answer("Who is the best football player in the world?\nWho are your best friends?\nWho is that strange guy over there?\nWhy do we need a nanny?\nWhy are they always late?\nWhy does he complain all the time?\nHow do you cook lasagna?\nHow does he know the answer?\nHow can I learn English quickly?"))
Output:  
who is the best football player in the world? 
who are your best friends? 
who is that strange guy over there? 
why do we need a nanny? 
why are they always late? 
why does he complain all the time?
how do you cook lasagna? 
how does he know the answer? 
how can i learn english quickly?
相关问题