likethevegetable
likethevegetable

Reputation: 304

lua string pattern matching - using specific words as char-sets

I would like to use "words" instead of individual characters in Lua's char-set functionality. My toy-example below should illustrate my problem.

https://www.lua.org/pil/20.2.html

--
print (string.find('Animal=Dog','Animal=[(Dog)(Cat)]')) -- gets a match, good
print (string.find('Animal=Cat','Animal=[(Dog)(Cat)]')) -- gets a match, good
print (string.find('Animal=DogCat','Animal=[(Dog)(Cat)]')) -- gets a match as expected, but not what I want
print (string.find('Animal=CatDog','Animal=[(Dog)(Cat)]')) -- to my surprise, this one matches

-- so I try to anchor the string for an exact match, but it yields nil?
print (string.find('Animal=Dog','^Animal=[(Dog)(Cat)]$')) -- nil, but this is what I think should work

Upvotes: -1

Views: 48

Answers (1)

None of those patterns do what you think they do. Parentheses aren't special inside of classes, so Animal=[(Dog)(Cat)] is the same as Animal=[()CDagot]. So it was never matching your whole string, but rather just Animal=C and Animal=D, which is why adding the anchors made it stop matching. Note that unlike regexes, Lua patterns don't support alternation, i.e., there's no way to do a single find to match what the regex Animal=(Dog|Cat) would match. You need to either modify your code to not rely on a single find, or get and use a library like LPeg to do the matching instead.

Upvotes: 1

Related Questions