Search code examples
luaanchorstring-matching

lua not handling anchors in string.find or string.match


This has been asked before at Pattern in lua with anchors not matching however I have a test case that shows that it still doesn't appear to work:

patterns = {
    'a@b',
    '^a@b',
    '[email protected]',
    'my-a@b',
    '[email protected]',
    '[email protected]$',
    '^[email protected]',
    '[email protected]$',
    '^[email protected]$',
}

test = "[email protected]"

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

I did the separate test:find vs string.find(test...) just to be sure there were no shenanigans.

Can someone enlighten me on how I can get my anchored patterns to work?


Solution

  • Some of the characters you are using (like . and -) have special meaning in pattern matching and you need to escape them. For example, using ^this%-is%-my%-a@b%.com and this%-is%-my%-a@b%.com$ should produce the expected results.