How to check if matching text is found in a string in Lua?

若如初见. 提交于 2019-12-04 14:59:36

问题


I need to make a conditional that is true if a particular matching text is found at least once in a string of text, e.g.:

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
    print ("The word tiger was found.")
else
    print ("The word tiger was not found.")

How can I check if the text is found somewhere in the string?


回答1:


You can use either of string.match or string.find. I personally use string.find() myself. Also, you need to specify end of your if-else statement. So, the actual code will be like:

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

or

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

It should be noted that when trying to match special characters (such as .()[]+- etc.), they should be escaped in the patterns using a % character. Therefore, to match, for eg. tiger(, the call would be:

str:find "tiger%("

More information on patterns can be checked at Lua-Users wiki or SO's Documentation sections.



来源:https://stackoverflow.com/questions/10158450/how-to-check-if-matching-text-is-found-in-a-string-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!