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

7

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

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

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

你们中的任何人都可以告诉我我做错了什么,我想做什么,或者指向一个好的参考,我可以获得有关Lua的字符串操作函数如何利用正则表达式的全面信息吗?

3个回答

13
Lua不使用正则表达式。Lua使用Patterns,它们看起来相似但匹配不同的输入。 .*也会消耗输入的最后一个?,所以在\\?上会失败。问号应该被排除。特殊字符用%转义。
"how[^?]*%?"

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

哦,谢谢。我觉得这真的让我很困惑,因为模式看起来很像正则表达式,但又有些不同。 - Uronym

9
根据手册,模式不支持交替。因此,"how.*"可以工作,但"(how|what).*"不行。kapep关于问号被.*吞噬的说法是正确的。有一个相关的问题:Lua模式匹配与正则表达式

-1

正如他们之前已经回答的那样,这是因为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?"))

输出:多少木头?

如果你想在一个更大的文本字符串中找到一个问题,那个函数也会帮助你。

例如:

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?

你捕获的不是单词,而是范围。字母H-O-W或者什么都没有,再次是相同的三个字母或者什么都没有(例如零次或一次),等等,然后是任何东西和“?”。你的函数捕获以“?”结尾的任何内容。尝试print(capture_answer("omgwtflol? extra")),并得到omgwtflol?返回。 - Oleg V. Volkov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接