Search code examples
stringfileluafindlua-5.1

Lua's string.find won't find pattern


I'm currently working on a program for my webpage in Lua 5.1 and got stuck in some strange stuff.

file=io.open("articles/" .. string.sub(string,1) .. "_1250.html")
fContent=file:read("*a")

nic,start=string.find(fContent,"<h1 style='text-align: center;'>")
print(fContent)
print(nic,start)
len=string.find(fContent,"</h1>",start)
name=string.sub(fContent,start+1,len-1)

returns

(...blah blah blah boring file(fContent)....)

     <h1 style='text-align: center;'>Article name</h1>
     <i id='desc'>Article description</i>

</div>
nil     nil

I also tried to find:

[[<h1 style='text-align: center;'>]]

or

"h1 style='text-align: center;'"

and it didn't work (returns nil)...


Solution

  • You need to escape the - in text-align within your string.find function.

    nic,start=string.find(fContent,"<h1 style='text%-align: center;'>")
    

    will do it.

    The reason why is because - is a special character. You can learn more about special characters here:

    Programming in Lua: Patterns