lua中string.find或string.match不能识别锚点的问题

此前已经有人在Pattern in lua with anchors not matching进行了这方面的讨论,但是我有一个测试案例表明它似乎仍然不起作用:

patterns = {
    'a@b',
    '^a@b',
    'a@b.com',
    'my-a@b',
    'my-a@b.com',
    'a@b.com$',
    '^this-is-my-a@b.com',
    'this-is-my-a@b.com$',
    '^this-is-my-a@b.com$',
}

test = "this-is-my-a@b.com"

for _, pattern in ipairs(patterns) do
    print(pattern .. ": " .. test .. "\n\tfind: " .. (test:find(pattern) or 'nil') .. "\n\tmatch: " .. (test:match(pattern) or 'nil'))
    print(pattern .. ": " .. test .. "\n\tfind: " .. (string.find(test, pattern) or 'nil') .. "\n\tmatch: " .. (string.match(test, pattern) or 'nil'))
end

我做了分开的 test:find vs string.find(test...),只是为了确保没有欺诈行为。

有人能告诉我如何使我的锚定模式起作用吗?

点赞
用户1442917
用户1442917

一些你使用的字符(比如.-)在模式匹配中有特殊含义,需要进行转义。例如,使用^this%-is%-my%-a@b%.comthis%-is%-my%-a@b%.com$ 可以得到预期的结果。

2016-09-04 04:59:41