如何检查是否在 Lua 的字符串中找到匹配的文本? [英] How to check if matching text is found in a string in Lua?
问题描述
如果在文本字符串中至少找到一次特定匹配文本,我需要创建一个条件为真,例如:
str = "这是一些包含老虎这个词的文本."如果 string.match(str, "tiger") 然后打印(老虎这个词被发现了.")别的打印(没有找到老虎这个词.")
如何检查是否在字符串中的某处找到文本?
有 2 个选项可以找到匹配的文本;string.match
或 string.find
.
两者都对字符串执行正则表达式搜索以查找匹配项.
string.find()
string.find(主题字符串,模式字符串,可选的起始位置,可选的普通标志)
返回 startIndex
&找到的子串的endIndex
.
plain
标志允许忽略模式,而是将其解释为文字.不是将 (tiger)
解释为与 tiger
匹配的正则表达式捕获组,而是在字符串中查找 (tiger)
.>
反过来说,如果你想要正则表达式匹配但仍然想要文字特殊字符(例如 .()[]+-
等),你可以用百分比对它们进行转义;%(tiger%)
.
您可能会将它与 string.sub
示例
str = 这是一些包含老虎这个词的文本.";如果 string.find(str, "tiger") 然后打印(找到了老虎这个词.")别的打印(没有找到老虎这个词.")结尾
string.match()
string.match(s, 模式, 可选索引)
返回找到的捕获组.
示例
str = 这是一些包含老虎这个词的文本.";如果 string.match(str, "tiger") 然后打印(找到了老虎这个词.")别的打印(没有找到老虎这个词.")结尾
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?
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
Example
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)
Returns the capture groups found.
Example
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
这篇关于如何检查是否在 Lua 的字符串中找到匹配的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!