javascript - RegExp 特殊字符转义
问题描述
我已经在正则表达式中弄乱了几个小时的特殊字符,并且必须承认我放弃了。
尝试制作密码测试功能,测试至少以下一项:小写、大写、整数和特殊字符。
特殊字符是“¤@+-£$!%*#?&().:;,_”。
我用这个函数来逃避它们:
//used to escape special characters [¤@+-£$!%*#?&().:;,_]
RegExp.escape = function(str) {
return String(str).replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
};
并在这两个测试中测试了正则表达式:
var pattern1=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[¤@\+-£\$\!%\*#\?&\(\)\.\:;,_]).{8,}$/g;
var regexVal1=pattern1.test(password);
var pattern2=new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[¤@\+-£\$\!%\*#\?&\(\)\.\:;,_]).{8,}$","g");
var regexVal2=pattern2.test(password);
结果是:
var password="AaBbCcDd";//both regexVal1 and regexVal2 is false
var password="AaBbCcDd90";//both regexVal1 and regexVal2 is true
var password="AaBbCcDd90#¤";//both regexVal1 and regexVal2 is true
结果var password="AaBbCcDd90";
应该是“假的”!
问题是:我做错了什么?
解决方案
The reason is -
has special meaning in character class. So \+-£
inside it means "all characters in table of Unicode codes from '+' up to '£'".
So you need escape '-' there.
And yes, you don't need to escape all other characters there
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[¤@+\-£$!%*#?&().:;,_]).{8,}$/g
should be fine for you
推荐阅读
- amazon-web-services - 我们可以为 AWS 中的默认 VPC 更改 Default VPC = No 吗?
- python - 使用来自爬虫的 kafka 获取数据
- java - 在 Spark 2.2.0 中设置 DEFAULT_MAX_TO_STRING_FIELDS
- apache - 尝试安装 ssl 证书后,我可以访问我的网站
- node.js - 命令行(@angular/cli)未安装在 Angular 6 中
- python - 使用循环遍历范围以每次选择一个值
- javascript - 当 foreach 完成时,Jquery 执行下一个功能
- python - 在 QTableView 中使用 QSortFilterProxyModel 过滤结果
- botframework - 使用 sourceEvent 在 bot 框架模拟器中显示按钮
- fullcalendar - fullcalendar:将图像放置在所有日子单元格的中心