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

我好奇为什么这不起作用,需要知道如何解决它;我试图检测一些输入是否是问题,我相当确信 string.match 是我需要的,但是:

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

返回 nil。我相当确定 Lua 的 string.match 使用正则表达式在字符串中查找匹配,因为我以前使用过通配符(.),但也许我不理解所有的机制? Lua 在其字符串函数中需要特殊的定界符吗?我在此处测试了我的正则表达式这里,因此,如果 Lua 使用常规正则表达式,似乎上面的代码将返回“how much wood?”。

你们中的任何人都可以告诉我我做错了什么,我想做什么,或者指引我到一个好的参考资料,让我了解 Lua 的字符串操纵函数如何利用正则表达式的全面信息?

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

点赞
stackoverflow用户897024
stackoverflow用户897024

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

.* 还会消耗输入中的最后一个 ?,所以它在 \\? 上失败了。应该排除问号。特殊字符使用 % 转义。

"how[^?]*%?"

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

2011-08-21 12:22:25
stackoverflow用户111886
stackoverflow用户111886

根据官方手册,Lua的模式匹配不支持交替匹配。

所以,"how.*"可以匹配成功,但是"(how|what).*"不能。

而且kapep关于问号在.*中被吞噬的说法是正确的。

还有一个相关问题:Lua模式匹配与正则表达式

2011-08-21 12:27:11
stackoverflow用户9155965
stackoverflow用户9155965

正如他们之前已经回答过的,这是因为 Lua 中的模式与其他语言中的正则表达式不同,但如果您还没有找到一个足够强大的模式来完成所有工作,您可以尝试这个简单的函数:

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?"))

输出: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?"))
输出:
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?
2020-03-29 02:13:45