Main Content

Finding literals rather than patterns in Lua

Archive - Originally posted on "The Horse's Mouth" - 2009-08-11 06:56:44 - Graham Ellis

Lua's string.find looks for a PATTERN ... it's not as big an sophisticated as a regular expression match (but then it's got nothing like as big a footprint!), but neither is it a literal match. So if I want to search a string for - literally - a ".", I need to protect it. I can do this either with a % character, or by providing an extra true parameter to my find, meaning "I really want literals"

Let's look for a dot:

pos,posend = string.find(sed,".",at,true)
if not pos then break end


string.find returns both the start and the end character numbers of the match; in the case of a single literal character match such as mine here, the two values will be identical and indeed I could have left out ,posend save for my desire to provide an illustration.

Complete example source here, courses on the subject here.