繁体   English   中英

正则表达式:只允许大写字母和特定数字

[英]Regex: ONly Allow Upper case AND specific numbers

我正在尝试创建正则表达式并在 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)

我无法创建正确的正则表达式。 有人可以帮忙吗?

利用

^(?=.*[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

暂无
暂无

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

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