如何检查在Lua的字符串中是否找到匹配的文本? [英] How to check if matching text is found in a string in Lua?
问题描述
如果在文本字符串中至少找到一次特定的匹配文本,例如:
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?
推荐答案
您可以使用string.match
或string.find
中的任何一个.我本人亲自使用 string.find()
.另外,您需要指定if-else
语句的end
.因此,实际代码如下:
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
或
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
应注意,当尝试匹配特殊字符(例如.()[]+-
等)时,应使用%
字符将它们转义为模式.因此,以匹配为例. tiger(
,呼叫为:
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%("
有关模式的更多信息,请访问 Lua-Users Wiki 或 SO的文档部分.
More information on patterns can be checked at Lua-Users wiki or SO's Documentation sections.
这篇关于如何检查在Lua的字符串中是否找到匹配的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!