Search code examples
lualua-patterns

Pattern in lua with anchors not matching


Why this does not match? I want to match the exact pattern 2 letters followed by 3 numbers

   s = "dd123"
   for w in string.gmatch(s, "^%a%a%d%d%d$") do
      print(w)
      matched = true
    end 

Solution

  • If you just want to see if a string matches a pattern, use string.match instead.

    s = "dd123"
    print(string.match(s, "^%a%a%d%d%d$")) -- dd123
    

    string.gmatch is for finding all matches in a string, and doesn't work correctly with ^ and $.