且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查一个单词是否在Lua的字符串中显示为整个单词

更新时间:2023-11-28 21:16:22

由于Lua中没有通常的\b单词边界,因此可以使用

Since there is no usual \b 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],一种边界模式;此类项目在任何位置都与空字符串匹配,以使下一个字符属于set而前一个字符不属于set.集合集的解释如前所述.主题的开头和结尾就像字符\0一样处理.

%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 \0.

您可以使用以下ContainsWholeWord函数:

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演示

要完全模仿\b行为,您可以使用

To fully emulate \b behavior, you may use

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

模式,因为\b匹配以下位置:

pattern, as \b 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.