简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM