繁体   English   中英

正则表达式允许超过指定的字符

[英]Regular Expression allows more than specified characters

嗨,我是正则表达式的新手,我尝试根据以下条件创建正则表达式:

  1. 最多允许 9 个字符

  2. 第一个字符必须大写

  3. 结束字符必须是 0-9

  4. 必须包含以下特殊字符($、%、#)

     /^[AZ][a-z0-9A-Z$#%]{3,9}(?=.*[#$%]).\\d+$/

我的正则表达式有什么问题?

^[A-Z](?=.*[#$%])[a-z0-9A-Z$#%]{1,7}\d$

您需要在开始时进行lookahead \\d+应该是\\d {3,9}应该是{1,7}

打破正则表达式

/^[A-Z][a-z0-9A-Z$#%]{3,9}(?=.*[#$%]).\d+$/
^ # Match the start of a string
[A-Z] # First character must be a capital letter
[a-z0-9A-Z$#%]{3,9} # The next 3-9 characters must be alphanumeric or one of $, # and %.
(?=.*[#$%]) # Look-ahead, requiring that some character be one of $, # and % (note that this is strictly after the 3-9 character check)
. # Match any character
\d+ # Match one or more numeric digits
$ # Match the end of the string

因此,将匹配像"Aaaa$^55555555555555555"这样的字符串。

您需要更改前瞻,可能将其移至 3-9 个字符检查之前。 您还需要缩小它的长度,因为您明确允许大写字母作为第一个字符,数字作为最后一个字符,因此您可能希望匹配 1-7 个字符而不是 3-9 .

暂无
暂无

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

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