模式^ u.meta(\.| $)无法正常工作 [英] Pattern ^u.meta(\.|$) not working as expected
问题描述
我有这种模式:
^u.meta(\.|$)
预期的行为
^u.meta(\.|$)
将匹配所有角色,例如:
^u.meta(\.|$)
will match all the roles like:
u.meta
u.meta.admin
u.meta.admin.system
u.meta.*
与以下内容不符的地方:
Where as it should not match something like below:
u.meta_admin
u.meta_admin_system
我已经通过 https://regex101.com/在线regexp tester
测试了这种模式.
I have tested this pattern with https://regex101.com/ online regexp tester
.
问题:
我必须使用lua
脚本实现此模式.
但得到invalid escape sequence near '\.'
:
I have to implement this pattern with lua
script.
but getting invalid escape sequence near '\.'
:
-- lua script
> return string.match("u.meta.admin", '^u.meta(\.|$)')
stdin:1: invalid escape sequence near '\.'
然后我尝试在该正则表达式中添加双精度\\
以及删除'\'转义字符,但返回nil:
And I tried adding double \\
as well as removing '\' escape char in that regexp but got nil in return:
-- lua script
> return string.match("u.meta.admin", '^u.meta(\\.|$)')
nil
> return string.match("u.meta.admin", '^u.meta(.|$)')
nil
推荐答案
请参见 Lua regex文档:
字符
%
用作那些魔术字符的转义符.
The character
%
works as an escape for those magic characters.
此外,Lua不支持(...|...)
替代.相反,我想您需要在此处使用单词边界,例如 %f[set]
边界模式:
Also, the (...|...)
alternation is not supported in Lua. Instead, I guess, you need a word boundary here, like %f[set]
frontier pattern:
%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
.
因此,您可以使用
return string.match("u.meta.admin", '^u%.meta%f[%A]')
仅在.
的末尾匹配:
return string.match("u.meta", '^u%.meta%f[\0.]')
要仅在admin
后没有字母或下划线时匹配,请使用否定的字符类[^%a_]
:
To match only if the admin
is not followed with a letter or an underscore, use a negated character class [^%a_]
:
return string.match("u.meta_admin", '^u%.meta%f[[^%a_]]')
print(string.match("u.meta", '^u%.meta%f[\0.]')) -- u.meta
print(string.match("u.meta.admin", '^u%.meta%f[\0.]')) -- u.meta
print(string.match("u.meta-admin", '^u%.meta%f[\0.]')) -- 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
注意要匹配字符串的末尾,而不是\0
,您可以安全地使用%z
(如此引用):
NOTE To match the end of the string, instead of \0
, you can safely use %z
(as @moteus noted in his comment) (see this reference):
%z
表示为0
%z
the character with representation0
这篇关于模式^ u.meta(\.| $)无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!