Vil*_*age 40 string lua conditional string-matching
如果在一串文本中至少找到一次特定的匹配文本,我需要创建一个条件,例如:
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.")
Run Code Online (Sandbox Code Playgroud)
如何检查文本是否在字符串中的某处找到?
hjp*_*r92 71
您可以使用两种string.match或string.find.我亲自使用string.find()自己.此外,您需要指定end您的if-else陈述.所以,实际的代码将是:
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
应该注意的是,当尝试匹配特殊字符(例如.()[]+-等)时,应该使用%字符在模式中对它们进行转义.因此,为了匹配,例如.tiger(,电话会是:
str:find "tiger%("
Run Code Online (Sandbox Code Playgroud)
可以在Lua-Users wiki或SO的文档部分检查有关模式的更多信息.