如果在文本字符串中至少找到一次特定的匹配文本,我需要设置一个条件为真,例如:
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.")
如何检查是否在字符串中的某处找到了文本?
有 2 个选项可以找到匹配的文本;string.match
或string.find
。
这两个都对字符串执行正则表达式搜索以查找匹配项。
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