开发者

Password Regular Expression

开发者 https://www.devze.com 2023-03-12 09:54 出处:网络
I need to come up with a regular expression that validates a string with the following requirements: Only contains alphanumeric and the following special characters: !@#$%^&*

I need to come up with a regular expression that validates a string with the following requirements:

  1. Only contains alphanumeric and the following special characters: !@#$%^&*
  2. Contains at least 1 of the special characters in the list above
  3. The required special character can appear anywhere in the string (for example: !abc, a!bc, abc!)

I keep getting close, but fail on one of the 开发者_如何学Goconditions.

Thanks!


The regular expression you're looking for is:

/^(?=.*[!@#$%^&*])[A-Za-z0-9!@#$%^&*]+$/

which will guarantee the string contains one of your special characters using (?=) positive lookahead.

--EDIT--

It appears Bohemian decided to completely ignore the comment section of my answer and edited the above example to remove its "unnecessary" character escaping. I really wish he hadn't because I believe my justification is correct, but there you have it. My original example was:

/^(?=.*[\!\@\#\$\%\^\&\*])[A-Za-z0-9\!\@\#\$\%\^\&\*]+$/


^(?=.*?[!@#$%\^&*])((?!_)[\w!@#$%\^&*])+$

It looks ensure the special character is found anywhere in the string. Once it finds it, it matches the rest of the string as long as the string consists of only word characters, digits, and the special characters.

Edit: The negativelookahead prevents _ (underscore).


Say you want minimum requirements of "at least one non-alphanumeric character, at least 8 characters". Use two look-aheads:

^(?=.*[^a-zA-Z0-9])(?=.{8,}$)

Other than that - let users choose the passwords they like.


This one seems to be working:

^.*(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).*$

If you would like to set an minimum length as well, use this (using 10 characters minimum):

^.*(?=.{10,})(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).*$

See rubular

0

精彩评论

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