可能出现在字符串中的字符模式

我知道应该使用string.match()来实现,但我无法匹配在字符串中“可能”存在的字符,例如:

teststring = "right_RT_12"

我可以轻松地执行如下操作:

string.match(teststring , 'righteye_RT_[0-9]+')

如果测试字符串的结尾总是“_[0-9]+”,那么这种方式很好,但测试字符串的结尾可能没有数字。在Lua中如何处理?

在Python中,我可以这样做:

re.search("righteye_RT(_[0-9]+)?", teststring)

我认为以下内容将起作用:

string.match(teststring, 'righteye_RT_?[0-9]+?')

但它没有。结果为“nil”。

然而,以下内容运行正常,但只能找到第一个数字:

string.match(teststring, 'righteye_RT_?[0-9]?')
点赞
用户107090
用户107090

尝试一下:

string.match(teststring, 'righteye_RT_?%d*$')

注意字符串末尾的锚点 $。如果没有锚点,%d* 将匹配空字符串,因此整个模式将匹配类似 righteye_RT_junk 的字符串。

2014-04-09 13:09:55
用户1009479
用户1009479

在 Lua 模式中,? 只能用于一个字符。你可以使用 or 来匹配两个模式:

local result  = string.match(teststring , 'righteye_RT_%d+')
             or string.match(teststring , 'righteye_RT')

注意,or 运算符是短路的。因此,它首先尝试匹配第一个模式,当且仅当第一个模式失败(返回 nil)时,它才会尝试匹配第二个模式。

2014-04-09 13:27:33