Lua string.match是否使用不规则的正则表达式? [英] Lua string.match uses irregular regular expressions?

查看:984
本文介绍了Lua string.match是否使用不规则的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).*\\?"))

返回零.我很确定Lua的string.match使用正则表达式在字符串中找到匹配项,因为我'在成功使用过通配符(.)之前,但也许我不了解所有机制? Lua的字符串函数中是否需要特殊的定界符?我已经在此处中测试了我的正则表达式,因此,如果Lua使用了正则正则表达式,似乎上面的代码会返回"how much wood?".

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

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

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?

推荐答案

Lua不使用正则表达式. Lua使用样式,它们看起来很相似,但是匹配不同的输入.

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 %.

"how[^?]*%?"

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

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.

这篇关于Lua string.match是否使用不规则的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆