【问题标题】:Lua string.match uses irregular regular expressions?Lua string.match 使用不规则的正则表达式?
【发布时间】:2011-10-31 13:52:52
【问题描述】:

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

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

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

谁能告诉我我做错了什么,我的意思是什么,或者给我一个很好的参考,在那里我可以获得关于 Lua 的字符串操作函数如何使用正则表达式的全面信息?

【问题讨论】:

    标签: regex lua


    【解决方案1】:

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

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

    "how[^?]*%?"
    

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

    【讨论】:

    • 哦,谢谢。我觉得这真的让我很困惑,因为模式看起来很像正则表达式,但又有点不同。
    【解决方案2】:

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

    所以虽然"how.*" 有效,但"(how|what).*" 无效。

    关于.* 吞下的问号,kapep 是对的。

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 您不是在捕捉单词,而是在捕捉范围。字母 H-O-W 或什么都没有,同样的三个字母或什么都没有(例如零或一次)等,然后是一大堆任何东西和“?”。您的函数捕获以结尾的任何内容?尝试print(capture_answer("omgwtflol? extra")) 并返回omgwtflol?
      猜你喜欢
      • 2014-02-13
      • 2019-11-11
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多