Pattern in lua with anchors not matching

2019-08-08 10:28发布

问题:

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 

回答1:

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 $.