Lua string.match 使用不规则正则表达式?
我很好奇为什么这不起作用,并且需要知道为什么/如何解决它;我正在尝试检测某些输入是否是一个问题,我很确定 string.match 是我所需要的,但是:
print(string.match("how much wood?", "(how|who|什么|哪里|为什么|何时).*\\?"))
返回 nil。我非常确定Lua的string.match使用正则表达式来查找字符串中的匹配项,因为我以前曾成功使用过通配符 (.),但也许我不理解所有机制? Lua 的字符串函数中是否需要特殊的分隔符?我已经在这里测试了我的正则表达式,所以如果Lua使用正则正则表达式,上面的代码似乎会返回“多少木材?”
。
你们中的任何人都可以告诉我我做错了什么,我打算做什么,或者为我提供一个很好的参考资料,在那里我可以获得有关 Lua 的字符串操作函数如何利用正则表达式的全面信息?
I'm curious why this doesn't work, and need to know why/how to work around it; I'm trying to detect whether some input is a question, I'm pretty sure string.match is what I need, but:
print(string.match("how much wood?", "(how|who|what|where|why|when).*\\?"))
returns nil. I'm pretty sure Lua's string.match uses regular expressions to find matches in a string, as I've used wildcards (.) before with success, but maybe I don't understand all the mechanics? Does Lua require special delimiters in its string functions? I've tested my regular expression here, so if Lua used regular regular expressions, it seems like the above code would return "how much wood?"
.
Can any of you tell me what I'm doing wrong, what I mean to do, or point me to a good reference where I can get comprehensive information about how Lua's string manipulation functions utilize regular expressions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Lua 不使用正则表达式。 Lua 使用模式,它们看起来相似但匹配不同的输入。
.*
还将消耗输入的最后一个?
,因此它在\\?
上失败。应排除问号。特殊字符用%
转义。正如 Omri Barel 所说,不存在交替运算符。您可能需要使用多种模式,每个模式对应句子开头的每个替代词。或者您可以使用支持正则表达式之类的表达式的库。
Lua doesn't use regex. Lua uses Patterns, which look similar but match different input.
.*
will also consume the last?
of the input, so it fails on\\?
. The question mark should be excluded. Special characters are escaped with%
.As Omri Barel said, there's no alternation operator. You probably need to use multiple patterns, one for each alternative word at the beginning of the sentence. Or you could use a library that supports regex like expressions.
根据手册,模式不支持交替。
因此,虽然
"how.*"
有效,但"(how|what).*"
却无效。kapep 关于问号被
.*
吞没的说法是正确的。有一个相关的问题:Lua模式匹配与正则表达式。
According to the manual, patterns don't support alternation.
So while
"how.*"
works,"(how|what).*"
doesnt.And kapep is right about the question mark being swallowed by the
.*
.There's a related question: Lua pattern matching vs. regular expressions.
正如他们之前已经回答的那样,这是因为 lua 中的模式与其他语言中的正则表达式不同,但是如果您尚未设法获得完成所有工作的良好模式,您可以尝试这个简单的功能:
如果您想在较大的文本字符串中查找问题,该函数也会为您提供帮助
。
As they have already answered before, it is because the patterns in lua are different from the Regex in other languages, but if you have not yet managed to get a good pattern that does all the work, you can try this simple function:
That function will also help you if you want to find a question in a larger text string
Ex.