我在使用OpenResty编写lua代码时,需要使用到lua的正则表达式,其中pattern是这样的,
--热水器设置时间
local s = '12:33'
local pattern = "(20|21|22|23|[01][0-9]):([0-5][0-9])"
local matched = string.match(s, "(20|21|22|23|[01][0-9]):([0-5][0-9])")
print(matched)
因为我的业务需求是,表示24进制的时间:23:09
但是我发现,这个pattern始终不能得到我想要的匹配结果。这个普通的pattern在其它的编程语言,比如C、C++,python,perl,PHP等中,都不会有啥问题的,为啥就行不通呢?
后来我查询了网上的资料,并逐个尝试不同的pattern,发现只要出现"|"就不行!
下面是我验证代码
#!/usr/bin/lua
--注意:lua正则表达式中没有|这个元字符
local s = '12:04'
print(string.match(s, "[01][0-9]:[0-5][0-9]"))
print(string.match(s, "[01]%d:[0-5]%d"))
print(string.match(s, "[0-1]%d:[0-5]%d"))
print(string.match(s, "(2[0-3]|[01][0-9]):[0-5][0-9]"))
local s = '23:59'
print(string.match(s, "2[0-3]:[0-5][0-9]"))
print(string.match(s, "2[0-3]:[0-5]%d"))
下面是输出结果的截图
为此,我找到lua正则表达式中的坑,它与其它语言都不同:
在正则表达式中没有"|"元字符
如果要表示多种可能并列的情况,只能写多个pattern了。