开发者

Confused on why this regular expression does not work?

开发者 https://www.devze.com 2022-12-20 17:06 出处:网络
/^(?=.*\\d)(?=.*[!@&.$#]).{7,16}$/ It should allow between 7 and 16 characters and contain at least 1 numeric character and 1 special character and can\'t start with a numb开发者_开发技巧er.I tr
/^(?=.*\d)(?=.*[!@&.$#]).{7,16}$/

It should allow between 7 and 16 characters and contain at least 1 numeric character and 1 special character and can't start with a numb开发者_开发技巧er. I tried testing it but it does not work?


The only thing that I assume "does not work", which is a bit of a vague problem description to be honest, is the fact that it CAN start with a digit. Besides that, it works as you described.

Fix it like this:

/^(?=.*\d)(?=.*[!@&.$#])\D.{6,15}$/

A short explanation (in case you did not write the regex yourself):

^             # match the beginning of the input
(?=           # start positive look ahead
  .*          #   match any character except line breaks and repeat it zero or more times
  \d          #   match a digit: [0-9]
)             # end positive look ahead
(?=           # start positive look ahead
  .*          #   match any character except line breaks and repeat it zero or more times
  [!@&.$#]    #   match any character from the set {'!', '#', '$', '&', '.', '@'}
)             # end positive look ahead
\D            # match a non-digit: [^0-9]
.{6,15}       # match any character except line breaks and repeat it between 6 and 15 times
$             # match the end of the input


The first two conditions are fulfilled but the third (must not start with a digit) is not. Because .* in ^(?=.*\d) does match when there is a digit at the first position.

Try this instead:

/^(?=\D+\d)(?=.*[!@&.$#]).{7,16}$/

Here \D (anything except a digit) ensures that that is at least one non-digit character at the start.

0

精彩评论

暂无评论...
验证码 换一张
取 消