Lua字符串操作模式匹配替代"|"

use*_*576 5 string lua parsing lua-patterns

有没有办法我可以做一个匹配的字符串模式,"ab|cd"因此它匹配任何一个"ab""cd"在输入字符串中.我知道你使用的东西就像"[ab]"一个模式,它将匹配任何一个"a""b",但这只适用于一个字母的东西.

请注意,我的实际问题要复杂得多,但基本上我只需要知道Lua的字符串操作中是否存在OR函数.我真的希望把的或东西,等各个侧面等图案但是,如果它与类似"hello|world"和匹配"hello, world!"与双方"hello""world"则这是伟大的!

Yu *_*Hao 5

在 Lua 模式中使用逻辑运算符可以解决大多数问题。例如,对于正则表达式[hello|world]%d+,您可以使用

string.match(str, "hello%d+") or string.match(str, "world%d+")
Run Code Online (Sandbox Code Playgroud)

or运算符的快捷电路确保字符串hello%d+首先匹配,如果失败,则匹配world%d+


Lor*_*ica 4

不幸的是,Lua 模式不是正则表达式,而且功能较弱。特别是它们不支持交替(|Java 或 Perl 正则表达式的竖线运算符),而这正是您想要做的。

一个简单的解决方法可能如下:

local function MatchAny( str, pattern_list )
    for _, pattern in ipairs( pattern_list ) do
        local w = string.match( str, pattern )
        if w then return w end
    end
end


s = "hello dolly!"
print( MatchAny( s, { "hello", "world", "%d+" } ) )

s = "cruel world!"
print( MatchAny( s, { "hello", "world", "%d+" } ) )

s = "hello world!"
print( MatchAny( s, { "hello", "world", "%d+" } ) )

s = "got 1000 bucks"
print( MatchAny( s, { "hello", "world", "%d+" } ) )
Run Code Online (Sandbox Code Playgroud)

输出:

你好
世界
你好
1000

该函数MatchAny会将其第一个参数(字符串)与 Lua 模式列表进行匹配,并返回第一个成功匹配的结果。