We help IT Professionals succeed at work.

Regex to allow only letter, number and underscores

J N
J N asked
on
1,669 Views
Last Modified: 2014-08-06
Hi,

im curious if it is possible to allow users to create a username with only letters numbers and underscores. the underscores cannot be back to back either

thanks in advance
Comment
Watch Question

Most Valuable Expert 2011
Author of the Year 2014

Commented:
Yes, it can be done.  It might be easier to use a couple of expressions instead of trying to do this all in one REGEX.
http://xkcd.com/1171/
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Please see http://iconoun.com/demo/temp_jaymenagy.php

<?php // demo/temp_jaymenagy.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28491049.html

function validate_password($pwd)
{
    $rgx
    = '/'      // REGREX DELIMITER
    . '['      // CHARACTER CLASS
    . '^'      // NEGATION - MATCH ANYTHING THAT IS NOT ONE OF THIS CLASS
    . 'A-Z'    // LETTERS
    . '0-9'    // NUMBERS
    . '_'      // UNDERSCORE
    . ']'      // END CHARACTER CLASS
    . '/'      // REGREX DELIMITER
    . 'i'      // CASE-INSENSITIVE
    ;
    if (preg_match($rgx, $pwd)) return FALSE;
    if (strpos($pwd, '__') === FALSE) return TRUE;
    return FALSE;
}

$dat = array
( 'abc123'
, 'abc123*'
, 'abc_123'
, 'abc__123'
)
;

foreach ($dat as $pwd)
{
    echo PHP_EOL . "<br>$pwd ";
    $sig = validate_password($pwd);
    if ($sig) echo "OK";
        else echo "FAIL";
}

Open in new window

Ed. note: Changed line 21 to use === instead of == comparison.
Dan CraciunIT Consultant
CERTIFIED EXPERT

Commented:
Here's a pure regexp solution, enforcing a minimum length too:
'/^(?!.*__).*\w{6}?$/im'

Open in new window

Replace 6 with how many characters you want your passwords to have.

PS @Ray: instead of [^A-Z0-9_] you can simply say \W

HTH,
Dan
J NUnicorn wrangler

Author

Commented:
Hi

it is possible to ensure that there are not only numbers?

in Ray's example '12352' would pass
Dan CraciunIT Consultant
CERTIFIED EXPERT

Commented:
Yup. Lookaheads are your friends:
'/^(?!.*__)(?=.*[A-Z]).*\w{6}?$/im'

Open in new window

Most Valuable Expert 2011
Author of the Year 2014

Commented:
Are there any other requirements you want to add to the question?  For example, some of the common requirements for passwords demand that they start with a letter and have at least one upper, one lower, one special, one number and contain no natural language words, etc.  The more detailed you can make the rule set, the more likely you will get the best answer.
J NUnicorn wrangler

Author

Commented:
Its not for a password its for usernames

i want to limit the ability to only accept particular charteres as i use - and .  to denote spaces in system processes.

i do not want a user name:
  - of only number
 - only underscores
  - number and underscores

i think having it start with letters is the best

ex :

 jaymenagy
jayme_nagy
j_nagy123

all are desirable
Dan CraciunIT Consultant
CERTIFIED EXPERT

Commented:
'/^[A-Z](?!.*__).*\w{5}?$/im'

Open in new window

Starts with a letter, does not have consecutive _, accepts only letters, numbers and _, at least 6 characters.
J NUnicorn wrangler

Author

Commented:
using rays code

function validate_password($pwd)
{
    $rgx
    = '/^[A-Z](?!.*__).*\w{5}?$/im';    
    ;
    if (preg_match($rgx, $pwd)) return FALSE;
    if (strpos($pwd, '__') === FALSE) return TRUE;
    return FALSE;
}

$dat = array
( 'abc123'
, 'abc123*'
, 'abc_123'
, 'abc__123'
, '12553'
)
;

foreach ($dat as $pwd)
{
    echo PHP_EOL . "<br>$pwd ";
    $sig = validate_password($pwd);
    if ($sig) echo "OK";
        else echo "FAIL";
}

Open in new window


i get

<br>abc123 FAIL
<br>abc123* OK
<br>abc_123 FAIL
<br>abc__123 FAIL
<br>12553 OK
Dan CraciunIT Consultant
CERTIFIED EXPERT
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
Most Valuable Expert 2011
Author of the Year 2014
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
J NUnicorn wrangler

Author

Commented:
Thanks guys !!!! big help

Regex is confusing as hell so i like the approach of taking it apart

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions