我需要制作一个条件判断,当在文本字符串中至少找到一次特定匹配文本时为真,例如:
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.")
如何检查字符串中是否包含某个文本?
我需要制作一个条件判断,当在文本字符串中至少找到一次特定匹配文本时为真,例如:
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.")
如何检查字符串中是否包含某个文本?
有两种方法可以找到匹配的文本; string.match
或者 string.find
。
这两种方法都会对字符串执行 Lua patten 搜索以查找匹配项。
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
返回找到的子字符串的 startIndex
和 endIndex
。
plain
标记允许忽略模式,并将其解释为文字。 而不是将(tiger)
解释为匹配tiger
的模式捕获组,它会在字符串中查找(tiger)
。
如果您想进行模式匹配,但仍要使用特殊字符(例如.()[]+-
等)的文字表示,则可以使用百分号对它们进行转义;%(tiger%)
。
您可能会与string.sub
结合使用此方法
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
string.match()
string.match(s, pattern, optional index)
返回找到的捕获组。
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:find("tiger")
- Ciprian Tomoiagăstring.find()
有第四个参数plain
,当设置为true时,将把第二个参数视为普通字符串。尽管('aa+bb'):find('a + b')
返回nil
(无匹配项),但('aa+bb'):find('a + b',1,true)
返回2,4
(找到一次匹配)。 - Feuermurmel