我正在嘗試創建正則運算式并在 javascript 中進行測驗。
規則:文本只能是 8 個字符。僅包含大寫字母和數字 1-5 不包含小寫字母或特殊字符或 6-7 數字。
例子:
12345678 -- false
a2345678 -- false
aabbccdd -- false
AABB33DD -- true // contains BOTH uppercase and
numbers between 1-5 and nothing else
AABB88DD -- false
AABBCCDD -- false
AABB3.DD -- false
代碼:
var pattern = new RegExp("^(?=.*[1-5])(?=.*[A-Z]). $");
pattern.test(code)
我無法創建正確的正則運算式。有人可以幫忙嗎?
uj5u.com熱心網友回復:
采用
^(?=.*[1-5])(?=.*[A-Z])[A-Z1-5]{8}$
請參閱正則運算式證明。
解釋
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
[1-5] any character of: '1' to '5'
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
[A-Z] any character of: 'A' to 'Z'
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
[A-Z1-5]{8} any character of: 'A' to 'Z', '1' to '5'
(8 times)
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/444968.html
標籤:javascript 正则表达式
上一篇:從字串C#正則運算式中提取標記
下一篇:匹配字串但忽略可選后綴?
