string 如何检查是否在 Lua 的字符串中找到匹配的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10158450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if matching text is found in a string in Lua?
提问by Village
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?
如何检查文本是否在字符串中的某处找到?
回答by hjpotter92
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:
您可以使用的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
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:
需要注意的是,当尝试匹配特殊字符(例如.()[]+-
等)时,应使用%
字符在模式中对其进行转义。因此,要匹配,例如。tiger(
,调用将是:
str:find "tiger%("
More information on patterns can be checked at Lua-Users wikior SO's Documentation sections.
可以在Lua-Users wiki或SO 的文档部分查看有关模式的更多信息。