简体   繁体   English

RegExp特殊字符转义

[英]RegExp special characters escape

I have messed around with special characters in regular expression for several hours now, and must admit that i give up. 我已经把正则表达式中的特殊字符弄乱了几个小时,必须承认我放弃了。

Trying to make a password test function, that test for at least one of the following: lowercase, uppercase, integer and special character. 尝试创建密码测试功能,该功能测试以下至少一项:小写,大写,整数和特殊字符。

The special characters are "¤@+-£$!%*#?&().:;,_". 特殊字符为“¤@ +-£$!%*#?&()。:;,_”。

I have used this function to escape them: 我已经使用此功能来转义它们:

//used to escape special characters [¤@+-£$!%*#?&().:;,_]
RegExp.escape = function(str) {
  return String(str).replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
};

And tested the regular expression in these two tests: 并在以下两个测试中测试了正则表达式:

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);

The results are: 结果是:

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

The result from var password="AaBbCcDd90"; 来自var password="AaBbCcDd90";的结果var password="AaBbCcDd90"; should be "false"! 应该是“假”!

The question is: What am i doing wrong?? 问题是:我在做什么错?

The reason is - has special meaning in character class. 原因是-在角色类中有特殊含义。 So \\+-£ inside it means "all characters in table of Unicode codes from '+' up to '£'". 因此\\+-£表示“ Unicode代码表中从'+'到'£'的所有字符”。

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 应该适合你

enough you add "\\" before "+" and "-"; 在“ +”和“-”之前加上“ \\”就足够了;

 var Regex1 =^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[¤@\+\-\£\$\!%\*#\?&\(\)\.\:;,_]).{8,}$

easy way for test your regular expressions is use this website: https://regex101.com/ 测试您的正则表达式的简单方法是使用以下网站: https : //regex101.com/


this example is also good: 这个例子也很好:

Use RegEx To Test Password Strength In JavaScript 使用RegEx在JavaScript中测试密码强度

var mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");

https://www.thepolyglotdeveloper.com/2015/05/use-regex-to-test-password-strength-in-javascript/ https://www.thepolyglotdeveloper.com/2015/05/use-regex-to-test-password-strength-in-javascript/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM