首页 > 解决方案 > 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";应该是“假的”!

问题是:我做错了什么?

标签: javascriptregex

解决方案


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


推荐阅读