lua 不处理 string.find 或 string.match 中的锚点

lua not handling anchors in string.find or 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:findstring.find(test...) 只是为了确保没有恶作剧。

谁能告诉我如何让我的锚定模式发挥作用?

您使用的某些字符(如 .-)在模式匹配中具有特殊含义,您需要对它们进行转义。例如,使用 ^this%-is%-my%-a@b%.comthis%-is%-my%-a@b%.com$ 应该会产生预期的结果。