Take the 2-minute tour ×

Recently programming in PHP, I thought I had a working Perl regular expression but when I checked it against what I wanted, it didn't work.

What is the right expression to check if something is a MD5 has (32 digit hexadecimal of a-z and 0-9).

Currently, I have /^[a-z0-9]{32}$/i

share|improve this question
Since when did hexadecimals go up to z? –  Anon. Feb 18 '10 at 2:01
add comment

6 Answers

up vote 30 down vote accepted





MD5 or SHA-1:


Also, most hashes are always presented in a lowercase hexadecimal way, so you might wanna consider dropping the i modifier.

By the way, hexadecimal means base 16:

0  1  2  3  4  5  6  7  8  9  A   B   C   D   E   F  = base 16
0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15 = base 10

So as you can see it only goes from 0 to F, the same way decimal (or base 10) only goes from 0 to 9.

share|improve this answer
You just saved me many painful google searches –  Andrew Harry May 27 '10 at 0:20
add comment

Should work a bit better, since MD5 hashes usually are expressed as hexadecimal numbers.

share|improve this answer
add comment

There is also the POSIX character class xdigit (see perlreref):

share|improve this answer
add comment

Well, an important point to consider is the fact that $ can match \n. Therefore:

E:\> perl -e "$x = qq{1\n}; print qq{OK\n} if $x =~ /^1$/"


The correct pattern, therefore, is:

share|improve this answer
add comment

Even easier and faster than RegEx as recommended by PHP Ctype Functions :

function is_md5($s){ return (ctype_xdigit($s) and strlen($s)==32); }
share|improve this answer
add comment

@OP, you might want to use /[a-f0-9]{32,40}/ , this can check for length greater than 32, such as those generated from sha1.

share|improve this answer
add comment

protected by Alix Axel Mar 15 '11 at 7:41

