簡體   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