使用正则表达式检测句尾的单词

我开始学习正则表达式。我的字符串可以是nxs_flo.nexus127.0.0.1nxs_flo.nexus.com

我想过滤掉只有nxs_flo.nexus类型的字符串。因此,我想测试一下我的字符串中是否有.nexus,并且它是在字符串的末尾。

这是我为了过滤出一个 . 而做的,但我不知道如何将其用于过滤出 .nexus 同时保证它在字符串的末尾:

if ngx.var.host:match("(.-)%.") == nil then

或者检测 .nexus,但它不起作用:

if ngx.var.host:match("(.*).nexus") == nil then
点赞
用户3832970
用户3832970

你可以使用

local host = [[nxs_flo.nexus]]
if host:match("%.nexus$") == nil then
    print("没有以'.nexus'结尾的字符串!")
else
    print("有以'.nexus'结尾的字符串!")
end
-- => 有以'.nexus'结尾的字符串!

请参见 在线 Lua 演示

该模式匹配:

  • %. - 字符串中的点 (literal . char)
  • nexus - 字符串中的 nexus 子字符串
  • $ - 字符串的结尾。
2018-02-07 14:28:51