为什么这个正则表达式允许插入符号? [英] Why is this regex allowing a caret?

查看:42
本文介绍了为什么这个正则表达式允许插入符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(带有 i 选项)会赢t 捕获您的字符串.

^(?=.*[0-9])(?=.*[a-z])[0-9a-z-]{17}$

在我看来,使用 Ignorecase 选项来避免这种问题并缩短正则表达式总是更安全.

http://regexr.com/3ars8

^(?=.*[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屋!

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