如何在Lua中检查字符串中是否有匹配的文本?

我需要做一个条件判断,如果一个特定的匹配文本在一段文本中至少出现一次,那么条件判断为真,例如:

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.")

我怎样才能检查文本是否在该字符串中出现过?

原文链接 https://stackoverflow.com/questions/10158450

点赞
stackoverflow用户1190388
stackoverflow用户1190388

有两种方法可以找到匹配的文本;string.matchstring.find

这两种方法都会对字符串进行正则表达式搜索以找到匹配项。


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

返回找到的子字符串的startIndexendIndex

plain标志允许忽略模式,并将其解释为字面量。而不是将(tiger)解释为匹配tiger的正则表达式捕获组,它在字符串中查找(tiger)

另一方面,如果您想进行regex匹配但仍希望具有文字特殊字符(例如.()[]+-等),则可以使用百分号对它们进行转义; %(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
2012-04-15 00:23:47