简体   繁体   中英

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"; 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 '£'".

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/


this example is also good:

Use RegEx To Test Password Strength In 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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