为什么这个正则表达式允许插入符号? [英] Why is this regex allowing a caret?
问题描述
(带有 i
选项)会赢t 捕获您的字符串.
^(?=.*[0-9])(?=.*[a-z])[0-9a-z-]{17}$
在我看来,使用 Ignorecase
选项来避免这种问题并缩短正则表达式总是更安全.
^(?=.*[0-9])(?=.*[A-z])[0-9A-z-]{17}$
Should match "17 alphanumeric chars, hyphens allowed too, must include at least one letter and at least one number"
It'll correctly match:
ABCDF31U100027743
and correctly decline to match:
AB$DF31U100027743
(and almost any other non-alphanumeric char)
but will apparently allow:
AB^DF31U100027743
Because your character class [A-z]
matches this symbol.
[A-z]
matches [
, \
, ]
, ^
, _
, `
, and the English letters.
Actually, it is a common mistake. You should use [a-zA-Z]
instead to only allow English letters.
Here is a visualization from Expresso, showing what the range [A-z]
actually covers:
So, this regex (with i
option) won't capture your string.
^(?=.*[0-9])(?=.*[a-z])[0-9a-z-]{17}$
In my opinion, it is always safer to use Ignorecase
option to avoid such an issue and shorten the regex.
这篇关于为什么这个正则表达式允许插入符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!