如何检查一个单词是否在 Lua 中的字符串中作为一个完整的单词出现 [英] how to check if a word appears as a whole word in a string in Lua

查看:23
本文介绍了如何检查一个单词是否在 Lua 中的字符串中作为一个完整的单词出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定如何检查一个单词是否在字符串中作为整个单词出现,而不是单词的一部分,区分大小写.例如:

not sure how to check if a word appears as a whole word in a string, not part of a word, case sensitive. for example:

Play 在字符串中

Info Playlist Play pause

但不在字符串中

Info Playlist pause
Info NowPlay pause

推荐答案

由于 Lua 中没有通常的  词边界,你可以利用一个 前沿模式 %f.%f[%a] 匹配一个字母的转换,%f[%A] 匹配相反的转换.

Since there is no usual  word boundary in Lua, you can make use of a frontier pattern %f. %f[%a] matches a transition to a letter and %f[%A] matches the opposite transition.

%f[set],一种前沿模式;这样的项目在任何位置匹配一个空字符串,使得下一个字符属于集合而前一个字符不属于集合.集合集的解释如前所述.主题的开头和结尾被当作字符 处理.

%f[set], a frontier pattern; such item matches an empty string at any position such that the next character belongs to set and the previous character does not belong to set. The set set is interpreted as previously described. The beginning and the end of the subject are handled as if they were the character .

您可以使用以下 ContainsWholeWord 函数:

You can use the following ContainsWholeWord function:

function ContainsWholeWord(input, word)
    return string.find(input, "%f[%a]" .. word .. "%f[%A]")
end

print(ContainsWholeWord("Info Playlist pause","Play") ~= nil)
print(ContainsWholeWord("Info Play List pause","Play") ~= nil)

参见 IDEONE 演示

要完全模拟  行为,您可以使用

To fully emulate  behavior, you may use

"%f[%w_]" .. word .. "%f[^%w_]"

pattern, as  匹配以下之间的位置:

pattern, as  matches the positions between:

  • 在字符串的第一个字符之前,如果第一个字符是一个单词([a-zA-Z0-9_])字符.
  • 在字符串的最后一个字符之后,如果最后一个字符是一个单词([a-zA-Z0-9_])字符.
  • 在字符串中的两个字符之间,其中一个是单词字符([a-zA-Z0-9_]),另一个不是单词字符([^a-zA-Z0-9_]).
  • Before the first character in the string, if the first character is a word ([a-zA-Z0-9_]) character.
  • After the last character in the string, if the last character is a word ([a-zA-Z0-9_]) character.
  • Between two characters in the string, where one is a word character ([a-zA-Z0-9_]) and the other is not a word character ([^a-zA-Z0-9_]).

注意 %w Lua 模式与 w 不同,因为它只匹配字母和数字,而不匹配下划线.

Note that %w Lua pattern is not the same as w since it only matches letters and digits, but not an underscore.

这篇关于如何检查一个单词是否在 Lua 中的字符串中作为一个完整的单词出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆