当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - Confused on why this regular expression does not work?

问题描述:

/^(?=.*\d)(?=.*[[email protected]&.$#]).{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 number. 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)(?=.*[[email protected]&.$#])\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
  [[email protected]&.$#]    #   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)(?=.*[[email protected]&.$#]).{7,16}$/

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: