String contains a certain word


I would like to check if a string contains a certain word.

String = "oi\ntchau\nhi\nbye"

The string is divided by \n (skip line), I would like to check between each line, if it contains the entire word, I already tried it and still can not.     

asked by anonymous 05.09.2014 / 09:17

3 answers


You can use the match or find functions to find the string you want. Both return a Boolean value indicating the presence of string

string.match("oi\ntchau\nhi\nbye", "hi")

Documentation match

string.find("oi\ntchau\nhi\nbye", "hi")

Documentation find

Both solve your problem if you just want to know whether or not it contains the searched string . The result can be used in if without problems.

If not, you need to be more specific in the question and show what you have already done, and point out the problem.

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

05.09.2014 / 15:05

To know if the integer is in string , you can use this:

procuro = "tchau"
dentrode = "oi\ntchau\nhi\bye"

string.match( "\n" .. dentrode .. "\n", "\n" .. procuro .. "\n" )


  • We use additional "\n" in procuro to search entire words only;

  • Similarly, we add the "\n" to dentrode , because if you search the whole word and it is at the beginning or end of the string, it will be found the same way.

    / li>
05.09.2014 / 17:46

Possibly like this:

--remover todos os /n
local result = string.gsub(s, "n", " ") -- remove line breaks

--Depois procurar as palavras
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
  print ("The word tiger was not found.")
05.09.2014 / 10:08