模式 ^u.meta(\.|$) 未按预期工作

Pattern ^u.meta(\.|$) not working as expected

我有这个模式:

^u.meta(\.|$)

预期行为

^u.meta(\.|$) 将匹配所有角色,例如:

u.meta
u.meta.admin
u.meta.admin.system
u.meta.*

它不应该匹配如下内容:

u.meta_admin
u.meta_admin_system

我已经用 https://regex101.com/ 在线测试了这个模式 regexp tester

问题:

我必须使用 lua 脚本来实现这个模式。 但得到 invalid escape sequence near '\.':

-- lua script

> return  string.match("u.meta.admin", '^u.meta(\.|$)')
stdin:1: invalid escape sequence near '\.'

我尝试在该正则表达式中添加双 \ 以及删除 '\' 转义字符,但在 return:

中得到 nil
-- lua script

> return string.match("u.meta.admin", '^u.meta(\.|$)')
nil

> return  string.match("u.meta.admin", '^u.meta(.|$)')
nil

参见Lua regex docs

The character % works as an escape for those magic characters.

此外,Lua 不支持 (...|...) 交替。相反,我猜你需要一个单词边界,比如 %f[set] frontier pattern:

%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 [=18=].

所以,你可以使用

return string.match("u.meta.admin", '^u%.meta%f[%A]')

只匹配 .:

的末尾或之前
return string.match("u.meta", '^u%.meta%f[[=11=].]')

要仅在 admin 后面没有字母或下划线时匹配,请使用否定字符 class [^%a_]:

return string.match("u.meta_admin", '^u%.meta%f[[^%a_]]')

参见 IDEONE demo to check the difference between the two expressions

print(string.match("u.meta", '^u%.meta%f[[=13=].]')) -- u.meta
print(string.match("u.meta.admin", '^u%.meta%f[[=13=].]')) -- u.meta
print(string.match("u.meta-admin", '^u%.meta%f[[=13=].]')) -- nil
print(string.match("u.meta", '^u%.meta%f[%A]')) -- u.meta
print(string.match("u.meta.admin", '^u%.meta%f[%A]')) -- u.meta
print(string.match("u.meta-admin", '^u%.meta%f[%A]')) -- u.meta
-- To exclude a match if `u.admin` is followed with `_`:
print(string.match("u.meta_admin", '^u%.meta%f[[^%a_]]')) -- nil

注意 要匹配字符串的结尾,而不是 [=18=],您可以安全地使用 %z(如 ) (see this reference):

%z    the character with representation 0