簡體   English   中英

RegExp特殊字符轉義

[英]RegExp special characters escape

我已經把正則表達式中的特殊字符弄亂了幾個小時,必須承認我放棄了。

嘗試創建密碼測試功能,該功能測試以下至少一項:小寫,大寫,整數和特殊字符。

特殊字符為“¤@ +-£$!%*#?&()。:;,_”。

我已經使用此功能來轉義它們:

//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";的結果var password="AaBbCcDd90"; 應該是“假”!

問題是:我在做什么錯?

原因是-在角色類中有特殊含義。 因此\\+-£表示“ Unicode代碼表中從'+'到'£'的所有字符”。

因此,您需要在其中逃脫“-”。

是的,您不需要在那里轉義所有其他字符

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

應該適合你

在“ +”和“-”之前加上“ \\”就足夠了;

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

測試您的正則表達式的簡單方法是使用以下網站: https : //regex101.com/


這個例子也很好:

使用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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM