What are ^.* and .*$ in regular expressions?

后端 未结 7 1094
臣服心动
臣服心动 2021-02-03 23:05

Can someone explain the meaning of these characters. I\'ve looked them up but I don\'t seem to get it.

The whole regular expression is:

/^.*(?=.{8,})(?=.         


        
7条回答
  •  执念已碎
    2021-02-03 23:56

    That looks like a typical password validation regex, except it has couple of errors. First, the .* at the beginning doesn't belong there. If any of those lookaheads doesn't succeed at the beginning of the string, there's no point applying them again at the next position, or the next, etc..

    Second, while the regex insures that each of those three kinds of character is present, it doesn't say anything about the rest of the string. That may have been a deliberate choice, but people usually try to insure that only those kinds of characters are present. In that case, you would want to change the first lookahead from (?=.{8,}) to (?=[A-Za-z@#$%^&+=]{8,}$).

    End result:

    /^(?=[A-Za-z@#$%^&+=]{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$/
    

提交回复
热议问题