tags:

views:

134

answers:

4

I'm desperatly searching for a regular expression that match anything between a to z, A to Z, 0 to 9 and "-". The same regular expression must not match if the string being checked is equal to "admin".

I tried this :

/^(?!admin)|([-a-z0-9]{1,})$/i

but it doesn't work, it match for the string admin even if I added the negative lookahead stuff.

I'm using this regex with PHP (PCRE).

+3  A: 

Is the regular expression the only tool available to you? It might be easier to do something like (Perl syntax):

if ($string ne "admin" && $string =~ /^[-a-z0-9]+$/i) { ...
Greg Hewgill
+1  A: 

I think it would work if you removed the "or" (|) operator. Right now you are basically saying, match if it is letters, etc. OR not equal to admin, so it always returns true because when it is equal to admin, it still matches the other expression.

newacct
+5  A: 

Doing "A and not B" in a single regex is tricky. It's usually better (clearer, easier) to do it in two parts instead. If that isn't an option, it can be done. You're on the right track with the negative look-ahead but the alternation is killing you.

/^(?!admin$)[-a-zA-Z0-9]+$/

In Perl's extended syntax this is:

/
  ^               # beginning of line anchor
  (?!             # start negative lookahead assertion
     admin        #   the literal string 'admin'
     $            #   end of line anchor
  )               # end negative lookahead assertion
  [-a-zA-Z0-9]+   # one or more of a-z, A-Z, 0-9, or '-'
  $               # end of string anchor
/x
Michael Carman
A: 

^(?![\.]*[aA][dD][mM][iI][nN][\.]*$)([A-Za-z0-9]{1,}$)

Try experimenting with a regex testing tool like the regex-freetool at code.google.com

Mazrick