Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

secured password with regular expression

I am very new to regular expression, I did a research and got a little understanding what I need is a password that matches those specifications

  1. any alphabetic character (at least one)
  2. any numeric character (at least one)
  3. no spaces
  4. special characters (0 or more)

what I got to is this

^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)(?!\S)$

which matches 1, 2, 3 specifications but not 4 I tried different stuff on 4, but I failed

can anyone help me ?

like image 822
Tareq Mansour Avatar asked Oct 13 '12 18:10

Tareq Mansour


1 Answers

You are very close. This seems to solve your problem:

preg_match("/^(?=.*[0-9])(?=.*[a-z])(\S+)$/i", $password)

I made two changes.

  1. Just a little shortening by using the i modifier (match case-insensitive). This allows to remove the A-Z`.
  2. The (?!\S) does not really help here, I think. Instead you can simply make your actual match only consist of non-space characters (the \S+). This will also immediately allow special characters in your password (really anything rexcept for spaces).

If you only want to allow a certain set of special characters, replace the \S by a character class containing letters, digits and all characters you want to allow. By the way, if you want to make sure your password has a certain minimum length, you could change that + into {8,} for example.

like image 65
Martin Ender Avatar answered Sep 30 '22 05:09

Martin Ender