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

查看:99
本文介绍了如何检查一个单词是否在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中没有通常的\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.

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

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